Domanda

I have something like this :

  • first level 1
    • 2nd level 1
      • 3rd level
      • 3rd level 2
    • 2nd level 2
  • first level 2

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>

È stato utile?

Soluzione

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

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

Altri suggerimenti

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.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top