dzimi dzimi - 6 months ago 10
Javascript Question

Give each element a class incremented by 1

I have this html:

<div class="nbhds-overlay active" style="display: block;">

<h3><href="#">one</a></h3>
<h3><href="#">two</a></h3>
<h3><href="#">three</a></h3>
<h3><href="#">four</a></h3>

</div>


I want to give each
h3
a class of
myclassSOMENUMBER
where
SOMENUMBER
is incremented by 1. I know how many elements there are, but it would be good if it could be done without knowing the number of elements as well ( i think that would be a recursive function? ).

Anyway, I tried the following, which gives each
h3
a class of
myclass1 myclass3
(understandably) , but I do not know how to target each one separately.

Basically in this concrete example they should have the following classes when done correctly:
myclass1
myclass2
myclass3
and
myclass4
respectively.

function classesForNbhds() {
var count = $('.nbhds-overlay h3').length;
for (var i = 1; i <= count; i++) {
$('.nbhds-overlay h3').addClass('myclass'+i);
i++;
};
}

classesForNbhds();

Answer

You can use $().each() method to iterate over the elements. Then assign the class using addClass()

$(".nbhds-overlay h3").each(function(i) {
  $(this).addClass("Myclass" + (i+1));
});

the first parameter in each method callback will be the index of the element. Here it is i

Comments