目录
replaceChild方法用新节点(新创建的节点或者已经存在的节点)替换某个子节点。
语法:
replaceChild(newnode,oldnode);
newnode 新节点 oldnode 要替换的节点
1.用已有的节点去替换
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=GBK">
<style>
*{
margin:5px;
padding:0;
}
#box{
border:1px solid blue;
width:300px;
height:200px;
}
#box1{
position:absolute;
left:50%;
top:0;
border:1px solid blue;
width:300px;
height:200px;
}
</style>
</head>
<body>
<div id="box"></div>
<button onclick='add()'>添加元素</button>
<button onclick='do_replace()'>用第一个元素去替换box1的最后一个元素</button>
<div id="box1" >
</div>
</body>
<script>
var i=1;
var box = document.getElementById("box");
function add(){
//创建元素box的子元素
var p = document.createElement("p");
p.innerText='这是box的P元素'+(i++);
box.appendChild(p);
}
//默认给box1创建一个子元素,方便测试
var box1 = document.getElementById("box1");
var p1 = document.createElement("p");
p1.innerText='这是box1的P元素';
box1.appendChild(p1);
function do_replace(){
if(!box.hasChildNodes()) return ;//如果没有子节点则返回
//用box的第一个元素去替换box1的最后一个元素
box1.replaceChild(box.firstChild,box1.lastChild);
}
</script>
</html>
效果图:
2.用新创建的节点去替换
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=GBK">
<style>
*{
margin:5px;
padding:0;
}
#box{
border:1px solid blue;
width:300px;
height:200px;
}
#box1{
position:absolute;
left:50%;
top:0;
border:1px solid blue;
width:300px;
height:200px;
}
</style>
</head>
<body>
<div id="box"></div>
<button onclick='add()'>添加元素</button>
<button onclick='do_replace()'>用第一个元素去替换box1的最后一个元素</button>
<button onclick='do_newReplace()'>用新创建的元素替换box1的最后一个元素</button>
<div id="box1" >
</div>
</body>
<script>
var i=1;
var box = document.getElementById("box");
function add(){
//创建元素box的子元素
var p = document.createElement("p");
p.innerText='这是box的P元素'+(i++);
box.appendChild(p);
}
//默认给box1创建一个子元素,方便测试
var box1 = document.getElementById("box1");
var p1 = document.createElement("p");
p1.innerText='这是box1的P元素';
box1.appendChild(p1);
function do_replace(){
if(!box.hasChildNodes()) return ;//如果没有子节点则返回
//用box的第一个元素去替换box1的最后一个元素
box1.replaceChild(box.firstChild,box1.lastChild);
}
var j=1;
function do_newReplace(){
var new_p = document.createElement("p");
new_p.innerText='这是新创建的的P元素'+(j++);
//用新创建的元素替换box1的最后一个元素
box1.replaceChild(new_p,box1.lastChild);
}
</script>
</html>
效果: