I’m having a problem selecting an specific li element in an un-ordered list. Although it’s not a major problem and I can find a way round it, I would really like to know why it’s not working.
My HTML:
<div id="myList">
<ul>
<li>something 1</li>
<li>something 2</li>
<li>something 3</li>
<li>something 4
<ul>
<li>sub something 1</li>
<li>sub something 2</li>
<li>sub something 3</li>
</ul>
</li>
</ul>
</div>
My problem is this:
$('#myList ul:first li:first').addClass('cool')
This adds the class to the “something 1” li tag. All well and good. But:
$('#myList ul:first li:last').addClass('cool')
Instead of adding the class to “something 4” li tag, it adds it to “sub something 3” li tag.
Why?
You are selecting all li-Tags down the Tree.
You might want to try this:
That way you only select direct child nodes of the previous node.