Let's presume you got a list with nested child lists.
<ul> <li></li> <li> <ul> <li></li> <li></li> </ul> </li> <li></li> </ul>
And use document.querySelectorAll()
to make a selection:
var ul = document.querySelectorAll("ul");
How can i use the ul
collection to get the direct child elements?
ul.querySelectorAll("> li"); // Gives 'Error: An invalid or illegal string was specified'
Let's presume ul
is cached somehow (otherwise i could have done ul > li
directly).
In jQuery this works:
$("ul").find("> li");
But it doesn't in native querySelectorAll
. Any solutions?
The querySelectorAll() method in HTML is used to return a collection of an element's child elements that match a specified CSS selector(s), as a static NodeList object. The NodeList object represents a collection of nodes. The nodes can be accessed by index numbers. The index starts at 0.
To retrieve all copies of a specific element, you can simply pass the name of the element as its argument. You can also select elements by other attributes like target or value : // return all elements with target="_blank" document. querySelectorAll("[target=_blank]"); // return all elements with value="red" document.
To add an event listener to the results from the querySelectorAll method: Use the forEach() method to iterate over the collection of elements. Call the addEventListener() method on each element in the collection.
The correct way to write a selector that is "rooted" to the current element is to use :scope
.
ul.querySelectorAll(":scope > li");
See my answer here for an explanation and a robust, cross-browser solution: https://stackoverflow.com/a/21126966/1170723
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With