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/
Comments
-
Rafael Adel almost 2 years
I'm really a beginner in Javascript and trying to add a
p
element inside adiv
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 almost 12 years@Rafael getElementsByTagName()
-
Rafael Adel almost 12 yearsYa, 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)
anddivElement.appendChild(el)
? -
Dave almost 12 years
divElement
, when assigned todocument.getElementsByTagName("div")[0]
, essentially already includes thedocument.body
portion since it's pointing to that specific div under the document object. Using "document.divElement.appendChild(el)" would be equivalent to repeating thedocument
portion twice (document.document.body), which is incorrect and why it fails. -
Derek 朕會功夫 almost 12 yearsMuch more easy with jQuery:
$("div").append($("<p>").html("This is paragraph 5.").attr("id","foo"));
Done.