public9nf
public9nf

Reputation: 1399

Loop through all h2 elements and add unique id

I need to add unique ids to all h2 tags with jquery. I dont know how to add unique ids actually all of my h2 tags get the same when i just use the attr function and i have no idea how to change that.

$('h2').attr("id", "rev3");

Upvotes: 2

Views: 1483

Answers (2)

Tom B.
Tom B.

Reputation: 2962

It is possible with each. You don't even need a seperate variable to hold the index:

$('h2').each(function(index, element) {
    $(this).attr('id', 'anid' + index);
});

Upvotes: 1

Daniel
Daniel

Reputation: 3514

You may use an implicit function inside jQuerys .each() like this

var id = 0;
$('h2').each(function(){
    $(this).attr("id", "rev" + id);
    id++;
})

.each() loops through all result array elements, while this reffers always to the current element.

Upvotes: 3

Related Questions