kan*_*han 1 html javascript dom clonenode
下面的代码按预期工作。
克隆节点.js
<!DOCTYPE html>
<html>
<body>
<script src="../js/CloneNode.js">
function myFunction(){
var the_node = document.getElementById("myList").lastChild;
var the_clone = the_node.cloneNode(true);
document.getElementById("myList").appendChild(the_clone);
}
</script>
<ul id="myList">
<li>Good morning</li>
<li>Hello</li></ul>
<p>Click on the button to CloneNode()</p>
<button onclick = "myFunction()">Copy it!</button>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
它也适用于以下代码:
<ul id="myList"><li>Good morning</li>
<li>Hello</li></ul>
Run Code Online (Sandbox Code Playgroud)
或者
<ul id="myList"><li>Good morning</li><li>Hello</li></ul>
Run Code Online (Sandbox Code Playgroud)
但是当我之前</ul>
在上面的 HTML 代码中输入换行符时,如下所示,我没有得到输出。因此,<li>
网页上没有添加元素。
<ul id="myList">
<li>Good morning</li>
<li>Hello</li>
</ul>
Run Code Online (Sandbox Code Playgroud)
HTML 代码中的缩进如何影响输出?或者有什么我错过的吗?
Element.lastChild
返回TextNode
节点以及Element
节点,新行字符TextNode
在查询时被解析为空,因此无论如何都要使其工作,请更改
var the_node = document.getElementById("myList").lastChild;
到
var the_node = document.getElementById("myList").lastElementChild;