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?
If used postfix, with operator after operand (for example, x++ ), the increment operator increments and returns the value before incrementing. If used prefix, with operator before operand (for example, ++x ), the increment operator increments and returns the value after incrementing.
++ increases the integer by one and += increases the integer by the number of your choice.
The most simple way to increment/decrement a variable is by using the + and - operators. This method allows you increment/decrement the variable by any value you want.
+= is an addition assignment (hence i changing value). j = i + 3 is what you're looking for.
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)}`);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With