0

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>

HalfWebDev
  • 7,022
  • 12
  • 65
  • 103
  • To be clear, you want first level 2 and 3rd level 2 in bold, and that's it? – bozdoz Feb 11 '12 at 18:10
  • marked answer will not cover **I want to addClass to all sibling** part. [see my answer](http://stackoverflow.com/a/9242610/880434) – Chamika Sandamal Feb 11 '12 at 18:16
  • @ChamikaSandamal yes,you are right in your way too. But if you go through the LIST again , the `3rd level 2` will only be affected as it is the only li element following the li element containing the anchor tag . So NEXT() does the work in this case . – HalfWebDev Feb 12 '12 at 07:40
  • @kushal: yes it's work for you for this extract structure. but if you changed the structure you have to change the JavaScript as well. better to have more generic solution for this kind of scenarios. – Chamika Sandamal Feb 12 '12 at 07:56
  • @ChamikaSandamal I understand you but I was aware of nextAll() method as well and knew when to use which, at the time i posted my question . Thanks for your concern,anyways ! – HalfWebDev Feb 12 '12 at 08:02
  • if you knew it already, i don't mind you are doing right or wrong since it is your code. i did my job. :). it's ups to you whether doing correct or wrong. – Chamika Sandamal Feb 12 '12 at 08:15

2 Answers2

1

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

$('li > a').parent().next().addClass('makebold');
Joe
  • 15,669
  • 4
  • 48
  • 83
0

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.

bozdoz
  • 12,550
  • 7
  • 67
  • 96