jQuery object index ignores jQuery.filter()

The method chain:

$("someSelector").filter("someMoreSpecificSelector").index()

should return the index of the element in the jQuery filtered array.

It actually returns the same as:

$("someSelector").index()

even though the jQuery array changed greatly when the filtering happened.

What am I doing wrong?

Upvotes: 0

Views: 44

Answers (1)

Karl-André Gagnon
Karl-André Gagnon

Reputation: 33880

As the Doc said :

index()

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.

http://api.jquery.com/index/

So it mean your code is currently checking its position among it children. So if you code look like that :

<div>
    <p>
    </p>
</div>
<div>
    <p id='yay'>
    </p>
</div>

Those 2 snippet will return the same thing :

$('div p').index(); //0
$('div p').filter('#yay').index(); //0

.index() accept argument. When passing a DOM object, you will have the current position of the object inside the jQuery object

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.

So you can use that :

var $collection = $("someSelector");
$collection.index($collection.filter('someMoreSpecificSelector'))

Upvotes: 1

Related Questions