Strontium_99
Strontium_99

Reputation: 1803

jQuery selector not logical

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?

Upvotes: 3

Views: 147

Answers (2)

lonesomeday
lonesomeday

Reputation: 237905

li:last is processed left-to-right. First, all the li elements that are descendants of the ul are selected. Because you are using a descendant selector rather than a child selector, this includes all the "sub" li elements. :last then selects the last of them to appear in the document, which is sub something 3.

You should use the child selector instead:

$('#myList ul:first > li:last').addClass('cool')

Upvotes: 3

bardiir
bardiir

Reputation: 14782

You are selecting all li-Tags down the Tree.

You might want to try this:

$('#myList ul:first>li:last').addClass('cool')

That way you only select direct child nodes of the previous node.

Upvotes: 6

Related Questions