简体   繁体   中英

appendChild method is not defined when using with a div element

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

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

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

Also, change:

document.divElement.appendChild(el); 

To:

divElement.appendChild(el);

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/

var div =  document.createElement("div");

document.lastChild.appendChild(div);

var a=[];

var n=[];



var txt=["Lovey", "komal", "Sona", "Purvi", "Sanchi"];

for (i=0; i<=txt.length; i++)

{
    a[i]=document.createElement("a");

    a[i].setAttribute("href","#");

    n[i].appendChild(n[i]);

    div.appendChild(n[i]);

    div.appendChild(a[i]);   

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM