Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript increasing variable

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?

like image 361
Shepard Avatar asked Sep 09 '13 11:09

Shepard


People also ask

How do you increment a variable in JavaScript?

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.

What is the difference between ++ and += in JavaScript?

++ increases the integer by one and += increases the integer by the number of your choice.

How do you increase variables?

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.

How do you increment a variable by 3?

+= is an addition assignment (hence i changing value). j = i + 3 is what you're looking for.


1 Answers

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)}`);
like image 94
Patsy Issa Avatar answered Oct 23 '22 23:10

Patsy Issa