如何在不定义变量的情况下使用 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' 标记。

我只是觉得你必须定义一个变量来创建一个新元素是荒谬的,而这种方式要优雅得多。我无法在网上找到任何关于此的信息。有谁知道如何让它按照我想要的方式工作,或者可能知道为什么它不能这样工作?

我不确定我是否理解您要实现的目标,但是如果您只想将 errorMessage 元素的 HTML 设置为某个 HTML,为什么不呢仅使用 innerHTML 属性?

errorMessage.innerHTML = '<p>Due to an egg allergy, your child will NOT receive the flu vaccine.</p>';

appendChildreturns追加child。所以我想你想要

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

如果你不止一次地做某事,创建一个抽象

function createP(text) {
  var p = document.createElement('p');
  p.appendChild(document.createTextNode(text));
  return p;
}

document.body.appendChild(createP('hello world'));