Search code examples
javascriptdomappendchild

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


Here is my code

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);

Here is my example:

http://jsfiddle.net/dennisboys/BRtYb/6/

developer.mozilla.org/en-US/docs/DOM/Node.appendChild, the doc says "Adds a node to the end of the list of children of a specified parent node.", but my example shows, it adds to the top of the list of children. Any idea why this happens? Thanks.


Solution

  • .createTextNode should be called on document.

    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);
    

    But by your example, you are using jQuery, so why not just do:

    $('#nav').append('<div>this is a new DIV</div>');
    

    And the demo.