I'm encountering a problem with a function I've created to tidy up some code. Take a look at the code snippet below for reference.
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 parameter e represents a DOM element, and if not provided, it defaults to this.cont, which is another earlier stored DOM element within the function.
This function iterates through all child elements, checks if they do not contain the 'keep' class, and removes any that do not match the criteria.
Although everything seemed to be functioning correctly, there's an issue with removing all elements from an element that contains two images and two inputs, none of which have the 'keep' class. The loop only reaches 2 instead of 4 before stopping.
Any assistance on resolving this would be highly appreciated.
/* UPDATE */
Credit goes to @pimvb and @Brett Walker for suggesting the final updated code snippet shown 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;
},