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.
Đang xem: Javascript array indexof() method
So I need to find .currentPlayer”s index within the player array.
HTML (very simplified):
JavaScript:
var player = $(“.player”), current = player.filter(“.currentPlayer”), index = current.index();
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);
You”re probably looking for
$(“div.player”).index($(“.currentPlayer”))http://jsfiddle.net/hmartiro/3Wzbd/
var position = 0;$(“.player”).each(function(i){if ($(this).hasClass(“currentPlayer”) == true) { position = i; }});
Thanks for contributing an answer to Stack Overflow!
Please be sure to answer the question. Provide details and share your research!
But avoid …
Asking for help, clarification, or responding to other answers.Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Post Your Answer Discard
By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy
Not the answer you're looking for? Browse other questions tagged jquery arrays class filter or ask your own question.
Site design / logo © 2022 Stack Exchange Inc; user contributions licensed under cc by-sa. rev2022.6.10.42345
Your privacy
By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.