Search code examples
jqueryindexingtraversalnodename

jquery find index() of same node name


I have this setup, just to find the index() of an element, but it should look at elements of the same level with the same nodename.

The returning numbers are not as expected. See the code comment. I want filteredByNodeNameIndex to be '2'.

Hope this example code is clear enough:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
    <title>TestDrive</title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>
    <script type="text/javascript" >
        function TestDrive()
        {
            var $obj = $("#div2");
            console.log("$obj.length:" + $obj.length); // returns: 1

            var $filtered = $obj.parent().children($obj[0].nodeName); // find all divs in same parent
            console.log("$filtered.length:" + $filtered.length); // returns: 3 

            var $obj_clone = $filtered.find($obj); // find original element again. Is something wrong here? 
            console.log("$objAgain.length:" + $obj_clone.length); // returns: 0

            var filteredByNodeNameIndex = $obj_clone.index(); // i want the number 2 here
            console.log("filteredByNodeNameIndex:" + filteredByNodeNameIndex); // returns: -1
        }
    </script>
</head>
<body onload="new TestDrive()">
    <div id="container"> 
        <!-- some random elements just for test -->
        <a></a>
        <div id='div1'></div>
        <div id='div2'></div>
        <span></span>
        <span></span>
        <a></a>
        <div></div>
        <a></a>
    </div>
</body>
</html>

Who can spot where this is wrong?


Solution

  • Try using .filter instead of .find:

    var $obj_clone = $filtered.filter($obj);
    

    The problem with .find is that it looks for children of the matched element, not siblings. From the docs:

    Get the descendants of each element in the current set of matched elements, filtered by a selector, jQuery object, or element.

    Compared to .filter:

    Reduce the set of matched elements to those that match the selector or pass the function's test.