Sometimes, we want to search for the immediate children of an element returned by querySelector with JavaScript.
In this article, we’ll look at how to search for the immediate children of an element returned by querySelector with JavaScript.
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.