HalfWebDev
HalfWebDev

Reputation: 7648

Traversing an unordered list -jQuery

I have something like this :

I want to addClass to all sibling li elements that follow the li elements containing anchor tag .

I tried doing this

$(li>a).next().addClass('makebold');

the $(li>a) does select the first level 1 li element and then according to next() which selects the immediately following sibling of the selected/matched element ,the element which should get BOLD by addition of class has to be first level 2 .

but the li elements-of 2nd and 3rd level are getting bold . I am wondering why ?

here is my html code for ul list

<ul> <li><a href="">first level 1</a> <ul> <li>2nd level 1 <ul> <li><a href="">3rd level</a></li> <li>3rd level 2</li> </ul> </li> <li>2nd level 2</li> </ul> </li> <li>first level 2</li>
</ul>

Upvotes: 0

Views: 264

Answers (2)

bozdoz
bozdoz

Reputation: 12860

How about this:

$('li > a').parent().find('li').addClass('makebold');

Selects li elements who are a descendent of li elements which have an anchor element as a child. I hope that I have understood your question correctly. Based on the other answers, I can only assume some of us don't understand what you're asking for.

Upvotes: 0

Joe
Joe

Reputation: 15802

You're selecting the element following the a, not following the li. Use this instead:

$('li > a').parent().next().addClass('makebold');

Upvotes: 1

Related Questions