The kind of removing a child node is always the case when you want to remove the child node from parent node. let say you got a dom object that has 3 child node you may want to remove all of them. how to do so you might using a for loop to loop through all its child node and remove all of them accordingly to the child node's index. you are right but will it work? let take a look at this.
e.g var parentDom = document.CreateElement("div");
var child1 = document.CreateElement(''div'');
var child2 = document.CreateElement(''div'');
var child3 = document.CreateElement(''div'');
//Append all the child to parentDom
parentDom.appendChild(child1);
parentDom.appendChild(child2);
parentDom.appendChild(child3);
//Let use 'removeChild' key word and FOR LOOP to remove them
for(var i = 0 ; i < parentDom.childNodes.length ; i++){
parentDom.removeChild(parentDom.childNode[i]);
}
You sure, this will work ? oops it won't, because when you remove the first element the second element will be moved to the first index, that make the second index blank which will cause the error.
//It will work like this
//Let use 'removeChild' key word and FOR LOOP to remove them
for(var i = 0 ; i < parentDom.childNodes.length ; i++){
parentDom.removeChild(parentDom.childNode[0]);
}
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment