Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Child selector using `querySelectorAll` on a DOM collection

Tags:

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?

like image 461
Husky Avatar asked Apr 17 '12 10:04

Husky


People also ask

What does the querySelectorAll () method do?

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.

How do I get values from querySelectorAll?

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.

Can you use addEventListener with querySelectorAll?

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.


1 Answers

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

like image 176
lazd Avatar answered Oct 26 '22 16:10

lazd