Monday, June 9, 2008

childNodes property of DOM object

A day when I paired with my friend, Sophy to code a javascript function, I found something that is unexpected behavior to both of us. It is the childNodes property of a dom object. I am not sure this is a default behavior of dom manipulation of javascript or not.

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:

Marcus Westin said...

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.

chamnap said...

Thanks. I agree with your idea. It was shocked me when I were coding.

Marcus Westin said...

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!

chamnap said...

No, I think you just go straight to the point. Anyway, thanks for your comments/ Cheers!

Thiruppathy Raja said...

what an exciting experience!/Hilorious! Delightful! True!
Property Development

Subscribe in a Reader