Search code examples
javascriptdomappendchild

appendChild does not add a node to the end of the list of children


According to docs https://developer.mozilla.org/en-US/docs/DOM/Node.appendChild, appendChild adds a node to the end of the list of children of a specified parent node.

However, my example shows it adds the child to the top of the list of children.

How is that? Any idea why it happens against the docs?

According to docs, these code should add a new div element to the end of targetArea node, instead, it adds to the top of the node.

var targetArea = document.getElementById('nav');
var div = document.createElement('div');
var snippet = document.createTextNode('this is a new DIV');
div.appendChild(snippet);
targetArea.appendChild(div);

My code online: http://jsfiddle.net/dennisboys/BRtYb/6/


Solution

  • It seems because you put <div> in <p> and the <div> will close the <p>.

    Also see this question. Putting <div> inside <p> is adding an extra <p>