Skip to content Skip to sidebar Skip to footer

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:

Solution 1:

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)}`);

Solution 2:

Try this:

varnumber = 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)

Solution 3:

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

Solution 4:

Use this operator

varnumber = 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);
}

Solution 5:

Try this

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

This is iterate single elements one by one rather than taking all elements with .content

Post a Comment for "Javascript Increasing Variable"