Traversing an unordered list -jQuery
-
28-04-2021 - |
سؤال
I have something like this :
- first level 1
- 2nd level 1
- 3rd level
- 3rd level 2
- 2nd level 2
- 2nd level 1
- 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>
المحلول
You're selecting the element following the a
, not following the li
. Use this instead:
$('li > a').parent().next().addClass('makebold');
نصائح أخرى
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.