PhasedEvolution PhasedEvolution - 2 months ago 13
HTML Question

Iterate over html elements with same class using .each

I have some div elements with the same class. I want to iterate through them. I am using jquery ".each" in order to do it. I also want to access each element individually and toogle its class so I need to get the index of the element within the class elements array. I currently have a code similar to this:

$('.the_div_class').each(function(i, obj) {

if("a certain condition") {

$('.the_div_class')[0].toggleClass('other_div_class'); // trying to access the index 0 of the array that contains the elements of that class;

}

}


However I receive an error saying "$(...)[0].toggleClass is not a function". If I don't specify an index I toogle all the elements of the array... I console.log the "$('.the_div_class')" array and get a structure similar to this:

[div.the_div_class, div.the_div_class, div.the_div_class, div.the_div_class, div.the_div_class, prevObject: r.fn.init[1]]


And if I console.log "$('.the_div_class')[0]" I get this:

<div class="the_div_class">


Why doesn't it work and what should I do in order to make it work?

Answer

The code $('.the_div_class')[0] will only get the first element that matches that selector in the DOM with that class naively, it doesn't work because it's no longer a jQuery object (hence it doesn't have the method .toggleClass()). Inside .each() you can use this to refer to the current element being iterated:

 $('.the_div_class').each(function(i, obj) {

   if("a certain condition") {

    $(this).toggleClass('other_div_class'); 

   }

 }

Note: To get a item by it's index in jQuery you can use .get(). For example:

 $('.the_div_class').get(0).toggleClass('other_div_class'); 
Comments