812jQuery: Getting the element index from a list of identical class elements
Let’s say you have a number of identical class elements:
<div class="myClass">One Title</div> <div class="myClass">Another Title</div> <div class="myClass">Brrrr</div> <div class="myClass">Zzzzzz</div>
And you want to get a particular element from this list.
var myArray = $(".myClass"); var thirdElement = myArray[2]; console.log(thirdElement); // <div class="myClass">Brrrr</div>
But note, that myArray[2] is the HTML element, not an jQuery object. If you want to access it via jQuery, you’ll have to “arm” it…
var myArray = $(".myClass"); var thirdElement = $(myArray[2]); console.log(thirdElement); // [<div class="myClass">Brrrr</div>]
Interrating over a jQuery selected list can be done with the each() function:
myArray.each(function(i, element){ var myElement = myArray[i]; // this // element }
myElement, element and this would all hold the same value at each iteration. i is obviously the index counter.
It’s also described quite clearly at the jQuery Docs, but I think it’s important enough to reiterate.