Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript querySelectorAll, how to match with only top elements?

I am using polymer.

Let say I have something in Template as follows

<ul>    
    <li>
        Home
    </li>
    <li>
        About
    </li>
    <li>
        Actions
        <ul>
            <li>
                Logout
            </li>
        </ul>
    </li>       
</ul>

In Ready function

var listNodes = this.querySelectorAll('ul > li');

I need help with this javascript query selector. The current query I applied gives me li of all ul from that template. But I want li of top ul only. I don't want all children li of template. I think changing it to proper query, I might get the right result. Please guide. Thanks.

like image 466
Vivek Muthal Avatar asked Feb 11 '23 18:02

Vivek Muthal


2 Answers

Using Mohit's comment. Able to figure out the answer.

var listNodes = this.querySelectorAll('ul:scope > li');
like image 141
Vivek Muthal Avatar answered Feb 13 '23 06:02

Vivek Muthal


A manual solution isn't all that bad, just find the first list and then iterate over its child elements:

var topList = document.querySelector('ul');

[].forEach.call(topList.children, function(el) {
  console.log(el);
});

Demo

If the list has an identifiable parent element (such as body or an element with id), you can use the immediate descendant operator (>).

Update

Since your question is tagged with jquery, here's another solution:

$('ul:first > li').each(function() {
  console.log(this);
});
like image 36
Ja͢ck Avatar answered Feb 13 '23 07:02

Ja͢ck