使用 JavaScript 向 DOM 添加元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2439642/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 00:20:41  来源:igfitidea点击:

Add an element to the DOM with JavaScript

javascripthtmldom

提问by john

I want add an element with JavaScript.

我想用 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:

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

</body>
</html>

Where is mistake?

错在哪里?

回答by naivists

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.

首先,您通过 来创建元素document.createElement。要设置其文本内容,您必须有一个“文本节点”来包裹您的文本。因此,您首先创建这样的文本节点,然后将其作为(唯一的)子节点添加到新对象中。

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 documentobject.

然后,将新创建的 DIV 元素添加到 DOM 结构中。您不必使用 查找 BODY 元素getElementsByTagName(),因为它作为document对象的属性存在。

回答by Marc B

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:

您的代码失败了,因为在您尝试插入那个全新的 div 时,body 标记为空,因此没有 firstChild 可以附加任何内容。将最后一行更改为:

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