Skip to content

Assign sequential numbering to elements [closed]

I am trying to iterate through elements to add sequential numbering to them.

Example: I have 6 input elements, I want to count how many inputs there are and then change their name to match their number “name=input1”, “name=input2”, and so on. I’m using a for loop to reset this each time an element is added or removed.

Here is the function I’ve been trying (and failing) to implement:

function count(){
    console.log(numChildren)
    var childCount = document.getElementById("items").childElementCount;
    console.log(childCount + " = number of children")
    numChildren = [];
    for (var i = 0; i < childCount; i++) {
        numChildren.push(i+1)
        document.querySelector("input[name*='item_name_']").name = "item_name_" + numChildren[i];
    }
};

Answer

Something like this would work:

const nodes = document.getElementById("items").children;
        
 for (var i = 0; i < nodes.length; i++) {

       nodes[i].setAttribute('name', 'item_name_'+(i+1));

  }
<html>

<body>
    <div id="items">
        <input type="text" name="item" />
        <input type="text" name="item" />
        <input type="text" name="item" />
        <input type="text" name="item" />
    </div>
</body>
</html>