javascript - When deleting DOM using removechild, you need to get the parent element first, but when insertbefore, you don't need to go to the parent element. and can be used directly
学习ing
2017-06-14 10:53:43
<!DOCTYPE HTML>
<html lang="en-US">
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<button id='btn'>创建元素</button>
<script type="text/javascript">
var btn = document.getElementById('btn');
//注册点击事件
btn.onclick = function(){
//创建一个元素
var h1 = document.createElement('h1');
h1.innerHTML = "这是新增h1标签";
console.log( h1 );
//使用appendChild的方式
//document.body.appendChild( h1 );
//使用insertBefore的方式
//是在父元素中,先找一个节点,然后插入到它之前
document.body.insertBefore(h1,btn); //新插入的节点是h1,作为第一个参数
}
</script>
</body>
</html>
<!DOCTYPE HTML>
<html lang="en-US">
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<p id="box">
<h2>删除操作</h2>
<p>段落1</p>
</p>
<button id='btn'>删除</button>
<script type="text/javascript">
//找父节点p
//var box = document.getElementById('box');
//找子节点h2
var h2 = document.getElementsByTagName('h2')[0];
var btn = document.getElementById('btn');
btn.onclick = function() {
//box.removeChild( h2 );
h2.parentNode.removeChild( h2 );
}
</script>
</body>
</html>
DOM API is designed this way.
body
is the parent element ofh1
.Although
h1
is anElement
, this method inheritsNode
.Node.insertBefore()
Grammar
Parameters and return values
insertedElement
is the inserted node, i.e.newElement
parentElement
is the parent node of the newly inserted nodenewElement
is the inserted nodereferenceElement
The node before insertingnewElement
Look at Node.removeChild again
Grammar
Parameters
child
is the child node to be removed.node
is the parent node of child.oldChild
Saves a reference to the deleted child node.oldChild === child
.body is also an element.