So I have these lines of javascript code that I need to remove all child nodes of the chosen select element and append new option elements to it. The option elements’ values are stored in the “personaggi” array.
So the code seems to work fine for “k” values of 0,1 and 2. When k=3 it doesn’t work correctly anymore and I can’t find out why. The function should be like this:
response=xmlhttp.responseText;
var personaggi=response.substr(1).split("+");
select=document.getElementById('select_personaggi');
var length=select.childNodes.length;
for(k=0;k<length;k++){
select.removeChild(select.childNodes[k]);
}
for(i=0;i<personaggi.length;i++){
var option=document.createElement('option');
option.setAttribute('value', personaggi[i]);
var text=document.createTextNode(personaggi[i]);
option.appendChild(text);
option.appendChild(text);
select.appendChild(option);
}
Hope I explained my problem well 🙂
You are basically removing elements from an array in a loop… this will never work properly. The size of the array changes over time, but you keep increment the index.
Either iterate over the nodes in reverse order, or do something like: