replaceChild()基本用法
replaceChild()
方法用新节点替换某个子节点。
这个新节点可以是文档中某个已经存在的节点,也可以是创建的新的节点。
node.replaceChild(newNode, oldNode);
参数 | 类型 | 描述 |
---|---|---|
newNode | Node object | 必需。您希望插入的节点对象。 |
oldNode | Node object | 必需。您希望删除的节点对象。 |
所有主流浏览器都支持该方法。
实例1:
<!DOCTYPE html>
<html>
<body>
<ul id="myList"><li>Coffee</li><li>Tea</li><li>Milk</li></ul>
<p id="demo">点击按钮来替换列表中的首个项目。</p>
<button onclick="myFunction()">试一下</button>
<script>
function myFunction()
{
var textnode=document.createTextNode("Water");
var item=document.getElementById("myList").childNodes[0];
console.log(item.childNodes);
item.replaceChild(textnode,item.childNodes[0]);
}
</script>
<p>首先创建一个新的文本节点。<br>然后替换首个列表项中的首个子节点。</p>
<p><b>注释:</b>本例用文本节点 "Water" 替换文本节点 "Coffee",而不是整个 LI 元素,这是替换节点的另一种方法。</p>
</body>
</html>
实例2:这里使用文档中已经存在的节点twoObj
替换oneObj
,结果是直接把oneObj
删掉了。不太懂是为什么?
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>删除替换克隆标签</title>
<style>
#one{
border: solid 1px blue;
background-color: green;
width: 300px;
height: 150px;
}
#two{
border: solid 1px blue;
background-color: aqua;
width: 250px;
height: 100px;
}
</style>
<script>
function replace(){
var oneObj = document.getElementById("one");
var twoObj = document.getElementById("two");
var bodyObj = oneObj.parentNode;
bodyObj.replaceChild(twoObj, oneObj);
}
</script>
</head>
<body>
<div id="one">
xxxxxxxxxx
</div>
<div id="two">
yyyyyyyyy
</div>
<input type="button" value="替换元素" onclick="replace()">
</body>
</html>
cloneNode()基本用法
cloneNode(deep)
方法创建节点的拷贝,并返回该副本。
cloneNode(deep)
方法克隆所有属性以及它们的值。
如果您需要克隆所有后代,请把 deep
参数设置 true
,默认为 false
。
所有主流浏览器都支持该方法。
实用cloneNode()
可以解决上面实例2的问题:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>删除替换克隆标签</title>
<style>
#one{
border: solid 1px blue;
background-color: green;
width: 300px;
height: 150px;
}
#two{
border: solid 1px blue;
background-color: aqua;
width: 250px;
height: 100px;
}
</style>
<script>
function clone(){
var oneObj = document.getElementById("one");
var twoObj = document.getElementById("two");
var bodyObj = oneObj.parentNode;
bodyObj.replaceChild(twoObj.cloneNode(true), oneObj);
}
</script>
</head>
<body>
<div id="one">
xxxxxxxxxx
</div>
<div id="two">
yyyyyyyyy
</div>
<input type="button" value="克隆和替换" onclick="clone()">
</body>
</html>