For example, you have a parent div container called "parentDiv", and it has two child containers. This parentDiv can be either added to the browser document or not, it doesn't matter. When we try add the child element of parentDiv to the browser document or to another dom element, the childNodes property of parentDiv is always updated from 2 to 0. Notice the following code:
var parentDiv = document.createElement("div");
var div1 = document.createElement("div");
div1.innerHTML = "hello1";
var div2 = document.createElement("div");
div2.innerHTML = "hello2";
parentDiv.appendChild(div1);
parentDiv.appendChild(div2);
alert(parentDiv.childNodes.length); //2
document.body.appendChild(div1);
alert(parentDiv.childNodes.length); //1
document.body.appendChild(div2);
alert(parentDiv.childNodes.length); //0
5 comments:
Correct me if I'm wrong, but this makes sense to me because:
A DOM element should be a child of exactly one parent node, or else you could potentially create a cyclical graph structure (seemingly not a good idea for the tree dom model).
Thus, appending an element to a new parent node should indeed remove it from any other parent node.
Thus, as you append div1 and div2 to the body element, your DOM tree correctly removes it from the parentDiv.
Please let me know what you think! Cheers.
Thanks. I agree with your idea. It was shocked me when I were coding.
I just re-read my comment and realized how pretentious it sounded. It was just an attempt to make it a step-by-step argument. Sorry!
I'm happy you agree. Cheers!
No, I think you just go straight to the point. Anyway, thanks for your comments/ Cheers!
what an exciting experience!/Hilorious! Delightful! True!
Property Development
Post a Comment