如何在不定义变量的情况下使用 document.createElement()
How to use document.createElement() without defining a variable
我很确定我已经知道这个问题的答案,但我有点想要一个解释。
我想创建和附加一个元素,而不必在变量中定义它(这对我来说似乎是一种浪费,而且是不必要的)。
var errorMessage = document.getElementById("errorMessage");
errorMessage.innerHTML = "";
errorMessage.appendChild(document.createElement('p').appendChild(document.createTextNode("Due to an egg allergy, your child will NOT receive the flu vaccine.")));
因此,这实际上将文本节点附加到 errorMessage 元素中,但不会生成"p"标签。
我只是认为,当这样更优雅时,您必须定义一个变量来创建新元素是荒谬的。我无法在网上找到任何关于这个的信息。有谁知道一种方法可以按照我想要的方式工作,或者可能知道为什么它不会以这种方式工作?
appendChild
返回追加的子项。所以我想你想要
var text = "Due to an egg allergy, your child will NOT receive the flu vaccine.";
document.getElementById("errorMessage")
.appendChild(document.createElement('p'))
.appendChild(document.createTextNode(text));
我不确定我是否理解您要实现的目标,但是如果您想简单地将errorMessage
元素的HTML设置为某些HTML,为什么不直接使用innerHTML
属性呢?
errorMessage.innerHTML = '<p>Due to an egg allergy, your child will NOT receive the flu vaccine.</p>';
如果你不止一次这样做,请创建一个抽象
function createP(text) {
var p = document.createElement('p');
p.appendChild(document.createTextNode(text));
return p;
}
document.body.appendChild(createP('hello world'));
相关文章:
- 正在寻找比$(document).ready慢的$(window).load的替代方案
- document.open/document.write没有正确地清除chrome中的文档——这是chrome的错误吗
- 如何用更合适的内容替换document.write
- document.styleSheets不返回任何内容
- jQuery document.ready not working
- $(document).height()在刷新时随机化值(Safari 5.1.10)
- reactjs this.refs vs document.getElementById
- 如何通过adf中的document.getElementById获取inputText字段值
- window.opener.document在ie中不起作用
- contentWindow.document.body is null
- document.applet.method在Mounatin Lion上抛出safari 6+JDK7异常
- document.getElementById(“st”).click();不起作用
- $(document).height和$(window).heaght都返回相同的值-使用的是正确的doctype
- AngularJS Navigation (li ng-repeat, create header li), DOM
- 使用Object.create()的角度服务继承
- jQuery document.ready停止代码
- document.getElementById并使用id名称
- 使用jQuery 1.8.1准备好多个$(document).是否有任何开销
- JavaScript's替换与document.create()结合的函数-这个代码是做什么的
- document.querySelector('.create-option:first-child')