Hi,
I should start by saying that I’m new to javascript, but not to programming in general. I don’t know if what I’m seeing is bug, just “the way it is”, or if there’s something I’m missing…
The function below should remove one or all elements by tag name:
[CODE]
function RemoveElementsByTagName(tagName, num){
var elements = document.getElementsByTagName(tagName);
for(x in elements){
if(x == num || !num){
if(elements[x]){
elements[x].parentNode.removeChild(elements[x]);
}
}
}
}
The div’s I’m trying to remove are pretty much just:
[CODE]
<div id=”test1″>
hello
</div>
<div id=”test2″>
goodbye
</div>
If I pass a number index to RemoveElementsByTagName() to remove just one of the div’s it works fine, but if I pass just tagName things don’t work quite as I’d expect:
It deletes the first div, elements[0], no problem, but, it then shifts what was elements[1] to elements[0]. So when the for(… as …) attempts to remove elements[1] it obviously runs into trouble, because elements[1] is no longer defined…
So my question is, why has javascript reassigned what was at index[1] to index[0] without me explicitly reassigning to the local array I declared as ‘elements’. And second, if this is javascript trying to be helpful, why doesn’t it update the for(… as …) loop iterations (decrement x) when it knows full well just it shifted what would be the next array element back one so it’s effectively jumped over it… I thought the whole point of having for(… as …) was that you could sit back and not have to worry about this sort of thing. Is this behaviour deliberate for some reason?
Or it could just be me doing something wrong, of course 🙂
I honestly do feel for web developers – I get the impression you spend half your time trying to accommodate various quirks or outright bugs (mostly cross-browser stuff). At least when programming in C your mistakes are usually your own.