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?
Use this operator
or
You can use the index parameter of the .each function callback instead of your own counter:
Try this:
Note: you could just use vanilla JS to assign the attribute
id
(no need to use jQuery)Use
this
in the each loop :Otherwise you are selecting all the elements with class
.content
JS only approach:
ES6/ES2015 syntax:
Try this
This is iterate single elements one by one rather than taking all elements with .content