Categories
JavaScript Answers

How to Search for the Immediate Children of an Element Returned by querySelector?

Spread the love

Sometimes, we want to search for the immediate children of an element returned by querySelector.

In this article, we’ll look at how to search for the immediate children of an element returned by querySelector.

Search for the Immediate Children of an Element Returned by querySelector

To search for the immediate children of an element returned by document.querySelector , we can use the :scope pseudoselector.

For instance, if we have the following HTML:

<div>  
  <p>  
    hello world  
  </p>  
</div>

Then we can get the p element given the div by writing:

const getChild = (elem) => {  
  return elem.querySelectorAll(':scope > p');  
};  
const div = document.querySelector('div')  
console.log(getChild(div))

We define the getChild function that calls elem.querySelectorAll to get all the p elements that are the immediate child of the given elem .

Then we get the div with querySelector and assign it to div .

And then we call getChild with div to get the p element in the div in a Nodelist.

Conclusion

To search for the immediate children of an element returned by document.querySelector , 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 *