Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery get index position of an element by class from an array

I've got multiple music players on a page and need to make an index of them to pull the position of the current player from. The issue is that the currentPlayer is not a child, so using .find or .filter and then .index will always return a value of 0 because nothing else is in the array.

So I need to find .currentPlayer's index within the player array.

HTML (very simplified):

<ul>
    <li>
        <article>
             <div class="player"></div>
        </article>
    </li>
    <li>
        <article>
             <div class="player currentPlayer"></div>
        </article>
    </li>
    <li>
        <article>
             <div class="player"></div>
        </article>
    </li>
</ul>

JavaScript:

var player  = $('.player'),
    current = player.filter('.currentPlayer'),
    index = current.index();
like image 503
technopeasant Avatar asked Sep 13 '12 19:09

technopeasant


People also ask

How can you get the position index of an item in an array?

To find the position of an element in an array, you use the indexOf() method. This method returns the index of the first occurrence the element that you want to find, or -1 if the element is not found.

How do you get the index of an object inside an array that matches the condition in jQuery?

The findIndex() method takes a function as the first parameter. This function is executed on every element of the array and the element for which the function returns “true” is the one that matched the specified condition. Thus the index of this matched element is stored in the index variable.

Can you use indexOf on an array?

indexOf() The indexOf() method returns the first index at which a given element can be found in the array, or -1 if it is not present.

How do you select an element by index?

The :eq() selector selects an element with a specific index number. The index numbers start at 0, so the first element will have the index number 0 (not 1). This is mostly used together with another selector to select a specifically indexed element in a group (like in the example above).


2 Answers

current.index() will search its parent for the element. so since current is an only child, it's zero.

You can pass a selector to .index; it'll tell jQuery to search inside that for your element.

var player  = $('.player'),
    current = player.filter('.currentPlayer'),
    index = current.index('.player');

Or, you can tell jQuery to search for a specific element inside of an array:

var player  = $('.player'),
    current = player.filter('.currentPlayer'),
    index = player.index(current);
like image 68
Rocket Hazmat Avatar answered Oct 06 '22 17:10

Rocket Hazmat


You're probably looking for

$('div.player').index($('.currentPlayer'))

http://jsfiddle.net/hmartiro/3Wzbd/

like image 25
Hayk Martiros Avatar answered Oct 06 '22 17:10

Hayk Martiros