Sometimes, we want to use querySelectorAll to retrieve direct children with JavaScript.
In this article, we’ll look at how to use querySelectorAll to retrieve direct children with JavaScript.
How to use querySelectorAll to retrieve direct children with JavaScript?
To use querySelectorAll to retrieve direct children with JavaScript, we can use the :scope > pseudoselector.
For instance, we write
const myDiv = document.getElementById("myDiv");
myDiv.querySelectorAll(":scope > .foo");
to get the myDiv element with getElementById.
Then we call querySelectorAll with the ":scope > .foo" select to get the direct children of the myDiv element with the foo class.
Conclusion
To use querySelectorAll to retrieve direct children with JavaScript, we can use the :scope > pseudoselector.