javascript - 我克隆 html 节点的方法不起作用

标签 javascript html

我是初学者 Java 脚本学习者,并按照一些在线教程进行改进。 我不太明白为什么我的代码不起作用,并且当我打开 chrome 开发人员工具时我没有看到任何问题?如果有人能告诉我我在这里做错了什么,我将非常感激。 记录后我发现,我意识到在 var the_node= document.getElementById("hh").lastChild; the_node 仍然未定义

<doctype! html>
<html>
<head>
    <title>clone a node</title>
    <script>
        function cloneNode1() {
            var the_node= document.getElementById("hh").lastChild;
            var cloned_node = the_node.cloneNode(true);
            document.getElementById("hh").appendChild(cloned_node);
        }   
    </script>
</head>
<body>
    <h1>welcome to Sarah's page</h1>
    <h2>here is the list of things which I really like</h2>
    <ul id="hh">
        <li>painting</li>
        <li>cooking</li>
    </ul>
    <p>click on the buttom to add to the list</p>
    <button onclick="cloneNode1()"> click me to colne</button>
</body>
</html>

最佳答案

问题是 element.lastChild 返回最后一个子节点,无论它是元素节点、文本节点还是注释节点。在您的情况下,它返回文本节点,其中包含换行符。元素内的空格被视为文本,文本被视为节点。

为了使其更清楚,如果您删除 hh 元素中的所有空格,它将起作用:

function cloneNode1() {
  var the_node= document.getElementById("hh").lastChild;
  var cloned_node = the_node.cloneNode(true);
  document.getElementById("hh").appendChild(cloned_node);
}   
<ul id="hh"><li>painting</li><li>cooking</li></ul>
<button onclick="cloneNode1()"> click me to colne</button>

但是,您不需要这样做。如果你想提取最后一个子元素,你只需要使用element.lastElementChild

这是代码片段,在更改方法后可以使用:

function cloneNode1() {
  var the_node= document.getElementById("hh").lastElementChild;
  var cloned_node = the_node.cloneNode(true);
  document.getElementById("hh").appendChild(cloned_node);
}   
<ul id="hh">
  <li>painting</li>
  <li>cooking</li>
</ul>
<button onclick="cloneNode1()"> click me to colne</button>

关于javascript - 我克隆 html 节点的方法不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34149020/

相关文章:

javascript - 使用 console.log 交换警报会导致代码失败

javascript - Photoshop 脚本 : iterating list of all layers withing the layerset is very slow

javascript - 在 react 中创建动态组件

javascript - 在 p5.js 中来回移动矩形时停止延迟

html - 菜单不起作用

javascript - Highcharts ajax 不工作

javascript - 这 2 个 glob 模式有什么区别吗?

javascript - HTML 文本溢出省略号检测

javascript - 暂停 youtube 视频并使用表单显示 div

javascript - 创建一个隐藏div的函数