Auto increment numbers in div id javascript

前端 未结 2 1064
南方客
南方客 2021-01-07 15:56

can somebody please help me? How to add auto increment number in div ID using javascript? I have four divs and I\'d like to have them automatically numbered (box1, box2, box

2条回答
  •  孤独总比滥情好
    2021-01-07 16:20

    There is an error in your code: <= should be only < if you are starting from 0!

    One possible solution is to use the node.setAttribute("attributeName", "attributeValue") method in order to set / change the attribute (in this case the id) of an element:

    A
    B
    C
    D

    The output is:

    If it is alright to use JS libraries (for example jQuery), then the transformation could be written even more succinctly:

    $(".something").each(function(index) {
        $(this).attr("id", this.id + index);
    });
    

    This code leads to the same output as above.

    The commented jQuery code:

    // find all elements with the class "something"
    $(".something")
    // call for each one of them 
        .each(
    // the function with parameter = current index
        function(index) {
    // take the current element
        $(this)
    // and set the attribute id to the new value
        .attr("id", this.id + index);
    });
    

提交回复
热议问题