Sometimes, we want to find DOM elements with CSS selectors with JavaScript.
In this article, we’ll look at how to find DOM elements with CSS selectors with JavaScript.
How to find DOM elements with CSS selectors with JavaScript?
To find DOM elements with CSS selectors with JavaScript, we can use the querySelectorAll
method.
For instance, we write:
<table>
<tbody>
<tr>
<td></td>
<td></td>
</tr>
</tbody>
</table>
to add the table with some td elements.
Then we can select the 2nd td by writing:
const cells = document.querySelectorAll("table > tbody > tr > td:nth-of-type(2)");
console.log(cells)
with querySelectorAll
.
Therefore, cells
is a node list object with the 2nd td inside.
Conclusion
To find DOM elements with CSS selectors with JavaScript, we can use the querySelectorAll
method.