appendChild method is not defined when using with a div element

11,853

Solution 1

getElementsByTagName(" ... ") returns a collection of elements.

var divElement = document.getElementsByTagName("div")[0];

Also, change:

document.divElement.appendChild(el); 

To:

divElement.appendChild(el);

Solution 2

One of your variable names is a bit misleading, namely divElement. Since you are using getElementsByTagName() (notice elements), it will return a list of elements, not a single one. Therefore, you should name the variable divElements to make it less confusing.

I've modified your code to work with a list of elements instead:

(function() {
    var divElements = document.getElementsByTagName("div");
    var el = document.createElement("p");
    var content = document.createTextNode("This is text");

    el.appendChild(content);

    for (var i = 0; i < divElements.length; i++) {
        divElements[i].appendChild(el);
    }
}());​

And a demo: http://jsfiddle.net/UmKYq/5/

Share:
11,853
Rafael Adel
Author by

Rafael Adel

About me

Updated on June 05, 2022

Comments

  • Rafael Adel
    Rafael Adel almost 2 years

    I'm really a beginner in Javascript and trying to add a p element inside a div element in this HTML :

    <!doctype html>
    <html>
        <head>
        </head>
    
        <body>
            <p>This is paragraph 1.</p>
            <p>This is paragraph 2.</p>
            <p>This is paragraph 3.</p>
            <p>This is paragraph 4.</p>
            <div>
                <p id="foo">This is paragraph 5.</p>
            </div>
            <script type="text/javascript" src="script.js"></script>
        </body>
    
    </html>
    

    using this code :

    (function(){
        var divElement = document.getElementsByTagName("div");
            el = document.createElement("p");
            content = document.createTextNode("This is text");    
        el.appendChild(content);
        document.divElement.appendChild(el);        
    }());
    

    But i get this error at line 6 :

    Uncaught TypeError: Cannot call method 'appendChild' of undefined

  • Andreas
    Andreas almost 12 years
  • Rafael Adel
    Rafael Adel almost 12 years
    Ya, that did it. Thank you and Andreas :) But may i ask what's the difference between document.divElement.appentChile(el), document.body.divElement.appendChild(el) and divElement.appendChild(el) ?
  • Dave
    Dave almost 12 years
    divElement, when assigned to document.getElementsByTagName("div")[0], essentially already includes the document.body portion since it's pointing to that specific div under the document object. Using "document.divElement.appendChild(el)" would be equivalent to repeating the document portion twice (document.document.body), which is incorrect and why it fails.
  • Derek 朕會功夫
    Derek 朕會功夫 almost 12 years
    Much more easy with jQuery: $("div").append($("<p>").html("This is paragraph 5.").attr("id","foo")); Done.