I want to add ID to each element of class .content
, and I want each ID to have integer increase by 1. Example:
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)}`);
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);
}
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
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));
});
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)