views:

47

answers:

2

I want add element with JS. I have code:

var collection = document.getElementsByTagName('body');
var a = document.createElement('div');
        a.innerHTML = 'some text';
            collection.item(0).firstChild.appendChild(a);

and simple HTML:

<html>
<head>
</head>
<body>

</body>
</html>

Where is mistake?

+1  A: 

This should do what you are looking for:

var newdiv = document.createElement("DIV");
newdiv.appendChild(document.createTextNode("some text"));
document.body.appendChild(newdiv);

First, you create the element by document.createElement. To set its text contents, you have to have a "text node" wrapping your text. So, you first create such text node and then add it as (the only) child to your new object.

Then, add your newly created DIV element to the DOM structure. You don't have to look for the BODY element with "getelementsbytagname", since it exists as a property of document object.

naivists
but It was only example, when I will want getElementsByTagName('xyz') and create element createElement('abc') and set innerHTML="<a href "some url">text</a>" ....How can I do that?
john
A: 

Your code is failing because at the time you try to insert that brand new div, the body tag is empty, and therefore there's no firstChild to append anything to. Change your last line to:

collection.item(0).appendChild(a);
Marc B