JavaScript incrementing variable

I want to add an identifier to each element of the .content class, and I want each identifier to have an integer increase of 1. Example:

 <div class="content" id="content_1"></div> <div class="content" id="content_2"></div> 

etc .. I wrote code that looks like this:

 var number = 1; $(".content").each(function() { $('.content').attr('id', 'content_' + number); number++; }); 

This code adds content_2 to both of them, not to content_1 and content_2 , if I have 3 elements with the class .content , they will all have the identifier content_3

Any ideas how I could fix this?

+6
source share
5 answers

Use this in every loop:

 $(".content").each(function() { this.id = 'content_' + number++; }); 

Otherwise, you select all elements with the class .content

JS approach only:

 var content = document.querySelectorAll('.content'); [].forEach.call(content, function(item, index) { item.id = "content_" + (index+1); }); 

Syntax ES6 / ES2015:

 let content = document.querySelectorAll('.content'); [].forEach.call(content, (item, index) => item.id = `content_${(index+1)}`); 
+18
source

Try the following:

 var number = 1; $(".content").each(function() { this.id = 'content_' + number; number++; }); 

Note: you can just use vanilla JS to assign id attribute (no need to use jQuery)

+7
source

You can use the .each function callback index parameter instead of your own counter:

 $(".content").each(function(i) { $(this).prop('id', 'content_' + (i+1)); }); 
+3
source

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); } 
0
source

try it

 var number = 1; $(".content").each(function() { this.id = 'content_' + number++; }); 

It is a repetition of individual elements one by one, and not acceptance of all elements with .content

0
source

Source: https://habr.com/ru/post/953477/


All Articles