首页 > 解决方案 > 将 HTML 元素存储在变量中

问题描述

<!DOCTYPE html>
<html>
<body>

<ul id="myList">
    <li>Coffee</li>
    <li>Tea</li>
</ul>

<p>Click the button to append</p>

<button onclick="myFunction()">Try it</button>

<script>
function myFunction() {
  let newLi = document.createElement("LI");
  let textNode = document.createTextNode("Water");
  let water = newLi.appendChild(textNode);
  console.log(water);    // water variable doesn't store the node object that represents the appended node
  document.getElementById("myList").appendChild(water);
}

</script>

</body>
</html>

我对 appendChild() 方法的返回值有疑问。定义说 appendChild() 的返回值是“表示附加节点的节点对象”。它不是字符串数据类型。所以,我只是试图将返回值存储在一个变量中(上面代码中的水变量)。但是,该变量只存储一个字符串数据类型。那是因为变量不能将 HTML 元素存储为它的值吗?

标签: javascripthtmlvariablesappendchild

解决方案


appendChild 确实返回附加的节点。当您使用 createTextNode('water') 时,您会注意到它也只返回文本。那是因为 textNode 只是文本。

如果您将 appendChild 与 html 元素一起使用,而不仅仅是 textNode,那么它将返回完整的元素。

在你的情况newLi

<li>Water</li>

如果你有

let newLi = document.createElement("LI");
let newSpan = document.createElement("SPAN");
let textNode = document.createTextNode("Water");
let water = newSpan.appendChild(textNode);
let waterItem = newLi.appendChild(newSpan);

这里waterItem<span>Water</span>


推荐阅读