I’m having an issue with a function I’ve written to “clean” up, see the code below and I’ll explain how it works underneath.
clean: function (e) {
var
els = null,
i = 0;
if (e === undefined) {
e = this.cont;
}
els = e.getElementsByTagName('*');
for (i=0;i<els.length;i++) {
if (els[i].className.search('keep') === -1) {
e.removeChild(els[i]);
}
}
return this;
},
The argument e is a dom element, if it isn’t supplied this.cont is also a dom element stored earlier in the whole function and e is defaulted to it.
The function loops through all of the child elements and checks it doesn’t have the class keep (fairly obvious what this does) and removes any that don’t match.
It all seemed to be working but I have an element which has 2 images and 2 inputs none with the class ‘keep’ but the variable i only gets to 2 and the loop stops (it should reach 4 and remove all four elements)
any help would be greatly appreciated.
/* UPDATE */
Thanks to @pimvb and and @Brett Walker the final code which works great is below.
clean: function (e) {
var
els = null,
i = 0;
if (e === undefined) {
e = this.cont;
}
els = e.getElementsByTagName('*');
i = els.length;
while (i--) {
if (els[i].className.search('keep') === -1) {
els[i].parentNode.removeChild(els[i]);
}
}
return this;
},
The
.getElementsByTagNamefunction returns aNodeListwhich is basically an array but is ‘live’, which means it’s updated automatically if you e.g. remove a child. So when iterating,els.lengthis changing, resulting in being2when you remove 2 children (there are4 - 2 = 2left). When having removed 2 children,i == 2so the loop will end prematurely to what you expect.To circumvent this and make it a ‘static’ array, you can convert it into an array like this, which does not update itself:
As Brett Walker pointed out, you can also iterate backwards, like this:
http://jsfiddle.net/pimvdb/cYKxU/1/
This will start at the last element. The
.lengthstill gets updated (i.e. becomes less), but this does not matter as you only used it at the beginning, and not during iterating. As a result, you don’t suffer from this ‘quirk’.