Add an element to the DOM with JavaScript

生来就可爱ヽ(ⅴ<●) 提交于 2020-02-10 01:50:48

问题


I want add an element with JavaScript.

I have the following 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:


This should do what you are looking for:

    var newdiv = document.createElement("div");
    newdiv.appendChild(document.createTextNode("some text"));
    document.body.appendChild(newdiv);
<html>
    <head></head>
<body>

</body>
</html>

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.




回答2:


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


来源:https://stackoverflow.com/questions/2439642/add-an-element-to-the-dom-with-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!