我很确定我已经知道这个问题的答案,但我想要一个解释。
我想创建并附加一个元素,而不必在变量中定义它(这对我来说似乎很浪费,而且没有必要)。
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));
关于javascript - 如何在不定义变量的情况下使用 document.createElement(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36847752/