<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>无标题文档</title>
<style type="text/css">
div {
margin: 1em;
}
#red{
border: solid 1px red;
}
#blue{
border: solid 1px blue;
}
</style>
<script>
/*
删除节点,该节点包含的所有子节点将同时被删除;
var node = ele.removeChild(node);
*/
window.onload = function() {
var ok = document.getElementById("ok");
ok.onclick = function() {
var red = document.getElementById("red");
var h1 = document.getElementsByTagName("h1")[0];
red.removeChild(h1);
}
}
</script>
</head>
<body>
<div id="red">
<h1>红盒子</h1>
</div>
<div id="blue">
蓝盒子
</div>
<button id="ok">删除</button>
</body>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>无标题文档</title>
<style type="text/css">
div {
margin: 1em;
}
#red{
border: solid 1px red;
}
#blue{
border: solid 1px blue;
}
</style>
<script>
/*
如果想要删除某个节点而又不知道它的父节点,可以使用parentNode()来获取父节点的引用
*/
window.onload = function() {
var ok = document.getElementById("ok");
ok.onclick = function() {
var blue = document.getElementById("blue");
var parent = red.parentNode;
parent.removeChild(blue);
}
}
</script>
</head>
<body>
<div id="red">
<h1>红盒子</h1>
</div>
<div id="blue">
蓝盒子
</div>
<button id="ok">删除</button>
</body>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>无标题文档</title>
<style type="text/css">
div{
margin: 1em;
}
#red{
border:solid 1px red;
}
#blue{
border:solid 1px blue;
}
</style>
<script>
/*
var oldNOde = ele.replaceChild(newNode, oldNode);
该方法能够把一个给定的父元素包含的一个子节点替换为另一个节点;
*/
window.onload = function(){ //定义当网页完成初始化之后执行的脚本函数
ok.onclick = function() {
var ok = document.getElementById("ok");
var red = document.getElementById("red");
var h1 = document.getElementsByTagName("h1")[0];
var h2 = document.createElement("h2"); //创建二级标题匀速,并引用指针
red.replaceChild(h2, h1); //把一级标题替换成二级标题
//这里替换的并不仅仅是标签,标签里面的东西也会被替换掉,也就说新生成的<h2>中没有内容
}
}
</script>
</head>
<body>
<div id="red">
<h1>红盒子</h1>
</div>
<div id="blue">
蓝盒子
</div>
<button id="ok">替换</button>
</body>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>无标题文档</title>
<style type="text/css">
div{
margin: 1em;
}
#red{
border: solid 1px red;
}
#blue{
border: solid 1px blue;
}
</style>
<script>
window.onload = function(){
var ok = document.getElementById("ok");
ok.onclick = function() {
var h1 = document.getElementsByTagName("h1")[0];
var blue = document.getElementById("blue");
var red = document.getElementById("red");
//首先用蓝盒子替换掉红盒子里面的一级标题
var del_h1 = red.replaceChild(blue, h1); //获得替换掉的一级标题
//将替换掉的一级插到红盒子前面
red.parentNode.insertBefore(del_h1, red);
}
}
</script>
</head>
<body>
<div id="red">
<h1>红盒子</h1>
</div>
<div id="blue">
蓝盒子
</div>
<button id="ok">替换</button>
</body>