Reputation: 1111
I want to add ID to each element of class .content
, and I want each ID to have integer increase by 1. Example:
<div class="content" id="content_1"></div>
<div class="content" id="content_2"></div>
etc. I wrote code which looks like this:
var number = 1;
$(".content").each(function() {
$('.content').attr('id', 'content_' + number);
number++;
});
This code adds content_2
to both of them rather than content_1
and content_2
, if I have 3 elements with .content
class all of them will have an ID of content_3
Any ideas how I could fix that?
Upvotes: 6
Views: 2238
Reputation: 11303
Use this
in the each loop :
$(".content").each(function(index) {
this.id = 'content_' + index;
});
Otherwise you are selecting all the elements with class .content
JS only approach:
var content = document.querySelectorAll('.content');
[].forEach.call(content, function(item, index) {
item.id = "content_" + (index+1);
});
ES6/ES2015 syntax:
let content = document.querySelectorAll('.content');
[].forEach.call(content, (item, index) => item.id = `content_${(index+1)}`);
Upvotes: 19
Reputation: 1695
Try this
var number = 1;
$(".content").each(function() {
this.id = 'content_' + number++;
});
This is iterate single elements one by one rather than taking all elements with .content
Upvotes: -1
Reputation: 1397
Use this operator
var number = 1;
$(".content").each(function() {
$('.content').attr('id', 'content_' + number);
number++;
});
or
var length = $(".content").length;
for(i=1;i<length;i++){
$('.content')[i].attr('id', 'content_' + i);
}
Upvotes: -1
Reputation: 78555
You can use the index parameter of the .each function callback instead of your own counter:
$(".content").each(function(i) {
$(this).prop('id', 'content_' + (i+1));
});
Upvotes: 4
Reputation: 123397
Try this:
var number = 1;
$(".content").each(function() {
this.id = 'content_' + number;
number++;
});
Note: you could just use vanilla JS to assign the attribute id
(no need to use jQuery)
Upvotes: 7