I'm having a little problem here, I want to use next() but I want to ignore nested lists... how can this be done? Right now next will select both the main list and the nested lists.
So say I have...
<ul id="mainlist">
<li>1</li>
<li class="selected">2</li>
<ul id="nested">
<li>A</li>
<li>B</li>
<li>B</li>
</ul>
<li>3</li>
</ul>
$(".selected").next().css("color", "red");
In this situation, the entire "nested" list color changes to red. But I would like the "3" to be red... What can I do in this situation?
Any help is appreciated, thank you.
NOTE: This is just an example problem, I'm actually trying to create navigation through list items but figured this code would be easier for an example.
Your issue (causing your code not to work as desired) is that the ul
tag isn't actually nested in the li
tag. The ul
tag is the next tag after the li
tag at the same level. If you mean for it to be nested, then your HTML should look like this:
<ul id="mainlist">
<li>1</li>
<li class="selected">2
<ul id="nested">
<li>A</li>
<li>B</li>
<li>B</li>
</ul>
</li>
<li>3</li>
</ul>
And, then your code will work as desired. You can see that here: http://jsfiddle.net/jfriend00/nfbPp/
If you actually mean for the HTML to be the way it is and you just want to select the next li
tag that's at the same level as the .selected
item, then you need different jQuery because .next()
will select the next sibling which is the ul
tag. You would need something like this:
$(".selected").nextAll('li:first').css("color", "red");
This will examine all the following siblings and select the ones that match the selector 'li:first'
(which will get just the first li
tag).
which you can see work here: http://jsfiddle.net/jfriend00/QrUtL/