hengecyche hengecyche - 7 months ago 36
Javascript Question

Looping childnodes in javascript

if(event.target.parentNode.className.indexOf('feat_img')!==1){
var innodes=event.target.parentNode.firstChild;



while(event.target.parentNode.childNodes){
console.log(innodes);
if(innodes.className=='img_preview'){
event.target.parentNode.removeChild(innodes);
}
innodes=event.target.parentNode.nextSibling;
}
}


This doesn't seem to be working. Am i doing it right?

Answer

Is this what you are looking for? I loop through the children and remove all img_preview.

var outer = document.getElementById('outer');
for (var i = 0; i < outer.childNodes.length; i++) {
    var inner = outer.childNodes[i];
    if (inner.className === 'img_preview') {
        outer.removeChild(inner);
    }
}

Note: I changed the loop end condition so we can be fairly sure it terminates (in the original code, if there is a child that isn't img_preview, we could get stuck in an infinite loop).

Comments