使用 JavaScript 向 DOM 添加元素 [英] Add an element to the DOM with JavaScript

查看:34
本文介绍了使用 JavaScript 向 DOM 添加元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用 JavaScript 添加一个元素.

I want add an element with JavaScript.

我有以下代码:

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

和简单的 HTML:

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

</body>
</html>

错在哪里?

推荐答案

这应该可以满足您的要求:

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>

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

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.

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

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.

这篇关于使用 JavaScript 向 DOM 添加元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆