user3023071
user3023071

Reputation: 31

Set elements' id in a for loop

I am trying to create a function, which counts the li elements, and then give them id="listItem1", id="listItem2" and so on. The problems is that j is always equal to 0, and I can't understand why. Here is the code. I am adding li elements to a list dynamically, but no matter how many they are, they always get id="listItem0" :

function countLi() {

    var liCount = document.getElementsByTagName("li").length;

    for (j = 0; j < liCount; j++) {

        document.getElementsByTagName("li")[j].id = "listItem" + j;
        document.getElementsByTagName("input")[j + 1].id = "checkbox" + j;
    }
}

Upvotes: 0

Views: 7446

Answers (2)

rafaelcastrocouto
rafaelcastrocouto

Reputation: 12161

SOLVED: http://jsbin.com/ERAqIVaj/1/edit?html,js,output

Don't use document.getElementsByTagName in your loop because of performance.

function countLi() {
    var li = document.getElementsByTagName("li"),
        input = document.getElementsByTagName("input");

    for (j = 0; j < li.length; j++) {
        li[j].id = "listItem" + j;
        input[j].id = "checkbox" + (j + 1);
    }
}

Upvotes: 1

Kanwaljit Singh
Kanwaljit Singh

Reputation: 4377

Try-

 function countLi() {

        var liCount = document.getElementsByTagName("li").length;

        for (var j = 0; j < liCount; j++) {

            document.getElementsByTagName("li")[j].id = "listItem" + j;
            document.getElementsByTagName("input")[j + 1].id = "checkbox" + j;
        }
    }

Or

function countLi() {

    var liCount = document.getElementsByTagName("li").length;
    var j;
    for (j=0; j < liCount; j++) {

        document.getElementsByTagName("li")[j].id = "listItem" + j;
        document.getElementsByTagName("input")[j + 1].id = "checkbox" + j;
    }
}

Upvotes: 0

Related Questions