Terf
Terf

Reputation: 51

jQuery .index(), confusing changes with argument

http://learn.jquery.com/using-jquery-core/understanding-index/

Perhaps I missed something in the article above, but I'm having some trouble understanding why the index number changes the way it does when an argument is used with .index().

For instance, with

<body> 
        <button id="console2">consoleSection2</button>
        <ul>
            <div class="test"></div>
            <li id="foo2">foo</li>
            <li id="bar2" class="test">bar</li>
            <li id="baz2">baz</li>
            <div class="test"></div>
        </ul>
        <div id="last"></div>
</body>

if I run

console.log( 
    "Index: " + $("#foo2").index()
);

I get "Index: 1", whereas if I run

"Index: " + $("#foo2").index("li")

I get "Index: 0".

Why does it change? To me, it would stay the same since "#foo2" is already in an "li" element.

Plus, why would it go to 0 as an Index? Is that because it's the first instance of "li" with an id of "#foo2"?

http://jsfiddle.net/f88zxaxo/

Upvotes: 1

Views: 40

Answers (1)

Pointy
Pointy

Reputation: 413720

When you pass a selector string into .index(), the return value indicates the location of the first matching element within the list of elements comprising the jQuery object.

Without an argument, .index() tells you the position of your element within its HTML container element among its siblings.

You get 1 back from $("#foo2").index() because the "foo2" element is at position 1 in the elements descended from the containing <ul> (and that's invalid markup, by the way). However, you get back 0 from $("#foo2").index("li") because the jQuery object has only one element in it, and it's an <li> element. If you tried $("#foo2").index("span"), you'd get -1 back.

Upvotes: 2

Related Questions