js DOM 操作----insertBefore( ) 的用法;
含义:在某个元素之前插入一个新的元素;
先来写一个带有三个段落的网页:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>insertBefore()</title>
</head>
<body>
<p class="first">我是第一个</p>
<p class="second">我是第二个</p>
<p class="third">我是第三个</p>
</body>
</html>
接下来我们动态创建一个段落添加到first 和second 之间;
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>insertBefore()</title>
</head>
<body>
<p id="first">我是第一个</p>
<p id="second">我是第二个</p>
<p id="third">我是第三个</p>
<script>
window.onload=function(){
var newp=document.createElement("p");//创建新的节点 p
newp.innerHTML="我是新加的"; //给新创建的节点p 添加内容
var second=document.getElementById("second"); // 获取原本的第二个节点p
document.body.insertBefore(newp,second); //在第二个节点之前插入新创建的节点
}
</script>
</body>
</html>
我们来看看 insertBefore() 的用法,
document.body.insertBefore(newp,second);
首先document.body是段落的父元素,insertBefore()里面有两个参数,
第一个参数表示要插入的节点,第二参数表示在哪个节点之前插入,
注意,第二个参数是可以为null 的,那么这个时候,只会在末尾插入节点了;