JavaScript increasing variable

前端 未结 5 1226
南方客
南方客 2021-01-18 11:37

I want to add ID to each element of class .content, and I want each ID to have integer increase by 1. Example:

5条回答
  •  深忆病人
    2021-01-18 11:47

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

提交回复
热议问题