On Feb 8, 4:01 pm, "RobG" <r...@iinet.net.auwrote:
Quote:
You might find it easier to iterate backwards using a while loop:
>
var n, i = ins.length;
while (n = ins[--i]) {
if (n.className == 'insert') {
n.parentNode.removeChild(n);
}
}
Agreed.
Quote:
The NodeList returned by getElementsByTagName is live. When you
remove ins[i] then the node that was ins[i+1] is now ins[i].
Incrementing the counter on then next loop skips that node to the one
that was ins[i+2].
>
When you work backwards (i.e. from highest to lowest index), inserting
or removing items at or beyond the current index list doesn't affect
iteration over all the original nodes.
Thanks to everyone, now I am clear on it.
getElementsByName / getelementsByTagName returns NodeList object (also
called HTMLCollection in older docs). In my coding I wrongly assumed
that NodeList is a kind of stripped down Array - without Array methods
and ability to store proprietary data, only with ability to iterate
using positive integer index.
In fact NodeList is Vector data type, so it automatically "shrinks" on
element removal with corresponding index renumbering of remaining
elements.
This way the safe way to remove elements is by going from the top to
bottom: in this case there is no index shift of remaining elements.
What wonders me now: one cannot directly remove elements from
NodeList, and a statement like
elm[i].parentNode.removeChild(elm[i])
changes the current NodeList in an indirect way (as a reflection of
DOM Tree change).
Does it mean that NodeList collection re-retrieved over and over
before any involving operation?