querySelectorAll 和 appendChild 的组合不起作用

Combination of querySelectorAll and appendChild is not working

我有多个定义列表,其中分布着许多 dt 元素。我想在每个 dt 中附加 button,但我不知道为什么我的代码不起作用。

这是我尝试过的:

const button = Object.assign(document.createElement("button"), {
  type: "button"
})

const descriptionTerms = document.querySelectorAll("dt")
// Or should I use:
// const descriptionTerms = [...document.getElementsByTagName("dt")]?

descriptionTerms.forEach(descriptionTerm => {
  descriptionTerm.appendChild(button)
})

我做错了什么?使用 ECMAScript 6 最优雅的方法是什么?

您的代码不起作用,因为您试图将同一个按钮对象附加到多个父对象,这是错误的。要解决此问题,请为每个 dt:

创建一个按钮
descriptionTerms.forEach(descriptionTerm => {
  const button = Object.assign(document.createElement("button"), {
    type: "button"
  })
  descriptionTerm.appendChild(button)
})

有关详细信息,请参阅 docs

The Node.appendChild() method adds a node to the end of the list of children of a specified parent node. If the given child is a reference to an existing node in the document, appendChild() moves it from its current position to the new position (there is no requirement to remove the node from its parent node before appending it to some other node).

另一种方法是克隆现有按钮:

This means that a node can't be in two points of the document simultaneously. So if the node already has a parent, the node is first removed, then appended at the new position. The Node.cloneNode() method can be used to make a copy of the node before appending it under the new parent. Note that the copies made with cloneNode will not be automatically kept in sync.