Manu
Manu

Reputation: 137

iterate parent li using each function jquery

This is my test HTML code:

<ul class="content">
<li class="data">
test1
    <ul>
        <li class="data">t1</li>
        <li class="data">t2</li>
    </ul>
</li>
<li class="data">
test2
    <ul>
        <li class="data">t3</li>
    </ul>
</li>
<li class="data">
test3
    <ul>
        <li class="data">t4</li>
    </ul>
</li>

jquery code is:

$(".content li").each(function(index, element) {
    console.log(element);
});

In this function, all the li lists having class 'data' under the main ul. But I need to iterate only the 3 parent li lists. How can I modify this jquery? Kindly help me :)

Upvotes: 2

Views: 1231

Answers (3)

Rohan Kumar
Rohan Kumar

Reputation: 40639

Try to use child selecter > like,

$(".content > li").each(function(index, element) {
    console.log(element);
});

Upvotes: 5

Manish Kr. Shukla
Manish Kr. Shukla

Reputation: 4477

in your jquery selector, add a > between .content and li..

$(".content > li").each(function (index, element) {
    console.log(element);
});

> looks for immediate child instead of all childs

Upvotes: 3

Mritunjay
Mritunjay

Reputation: 25882

You can even use .children like bellow

$(".content").children('li').each(function(index, element) {
    console.log(element);
});

DEMO

Upvotes: 0

Related Questions