views:

31

answers:

1

Not sure why this is happening. But everytime I do (elem).index(); , it always returns -1 . Why is that?

How can I find the index of an object?

+2  A: 

From the jQuery.index() documentation, among a lot of examples:

Return Values

If no argument is passed to the .index() method, the return value is an integer indicating the position of the first element within the jQuery object relative to its sibling elements.

If .index() is called on a collection of elements and a DOM element or jQuery object is passed in, .index() returns an integer indicating the position of the passed element relative to the original collection.

If a selector string is passed as an argument, .index() returns an integer indicating the position of the original element relative to the elements matched by the selector. If the element is not found, .index() will return -1.

Note the last sentence. Apparently elem is simply not found. Verify your selector and/or the element.


Update as per the comments, you're likely calling it at the wrong moment. Here's an SSCCE, copy'n'paste'n'run it.

<!DOCTYPE html>
<html lang="en">
    <head>
        <title>SO question 3740385</title>
        <script src="http://code.jquery.com/jquery-latest.min.js"&gt;&lt;/script&gt;
        <script>
            alert('Before DOM ready: ' + $(".nav ul li:first").index()); // Can return -1.

            $(document).ready(function() {
                alert('After DOM ready: ' + $(".nav ul li:first").index()); // Must return 0.
            });
        </script>
    </head>
    <body>
        <div class="nav">
            <ul>
                <li>item</li>
                <li>item</li>
                <li>item</li>
            </ul>
        </div>
    </body>
</html>

See also:

BalusC
But it can select it in firebug, so my selectors work, but it still gives me -1. Here's an example, `$(".nav ul li:first").index();` returns -1, but $(".nav ul li:first") is a working selector.
Trip
It gives 0 here. [Demo](http://jsfiddle.net/ujcaf/). Probably you're calling it at the wrong moment (before the DOM has loaded). Put it in `$(document).ready()`.
BalusC
Maybe its an old version of js I'm using or it doesn't work in firebug. I'm using this instead `$(".nav ul li:first").prevAll().length;`
Trip
Just use the latest. You can use the script URL as in the above example. You're free to include it in your pages, it's from a [CDN](http://docs.jquery.com/Downloading_jQuery#CDN_Hosted_jQuery).
BalusC
Yah thanks, something bigger at stake here is probably preventing this from working. Thanks anyway.
Trip