Here's my code:
function listDesserts (){
var dessertList = ["pudding", "cake", "toffee", "ice cream", "fudge", "nutella"];
var i = 0;
while (i< dessertList.length){
var ul = document.getElementById("thelist");
var nli = document.createElement("li");
var nliID = 'item-' +i;
nli.setAttribute('id', nliID);
nli.setAttribute('class', 'listitem');
nli.innerHTML = dessertList[i];
ul.appendChild(nli);
i++;
}
}
Since I'm setting the li tags IDs based on the number items in my array, i
sets it to zero as it should. Rather I want to modify i
so that it sets the IDs beginning with 1 without it skipping the first array member. I've tried a few things but I'm missing this. Anybody?
Here's my code:
function listDesserts (){
var dessertList = ["pudding", "cake", "toffee", "ice cream", "fudge", "nutella"];
var i = 0;
while (i< dessertList.length){
var ul = document.getElementById("thelist");
var nli = document.createElement("li");
var nliID = 'item-' +i;
nli.setAttribute('id', nliID);
nli.setAttribute('class', 'listitem');
nli.innerHTML = dessertList[i];
ul.appendChild(nli);
i++;
}
}
Since I'm setting the li tags IDs based on the number items in my array, i
sets it to zero as it should. Rather I want to modify i
so that it sets the IDs beginning with 1 without it skipping the first array member. I've tried a few things but I'm missing this. Anybody?
-
3
Maybe just using
i+1
instead ofi
in the loop body? – Uhehesh Commented Dec 9, 2012 at 23:30 -
@Uhehesh That should be answer.
=]
– Fabrício Matté Commented Dec 9, 2012 at 23:33
2 Answers
Reset to default 3As you are iterating an array, the counter variable should always run from 0
to length-1
. Other solutions were possible, but are counter-intuitive.
If you have some one-based numberings in that array, just use i+1
where you need it; in your case 'item-'+(i+1)
.
Btw, you might just use a for
-loop instead of while
.
Use var i = 1
;
and use i-1
where you currently have i
var i = 1;
while (i< dessertList.length-1){
var ul = document.getElementById("thelist");
var nli = document.createElement("li");
var nliID = 'item-' + (i-1); //<----- here
nli.setAttribute('id', nliID);
nli.setAttribute('class', 'listitem');
nli.innerHTML = dessertList[i-1]; //<----- and here
ul.appendChild(nli);
i++;
}