Categories
JavaScript Answers

How to use querySelectorAll to retrieve direct children with JavaScript?

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *