1. 程式人生 > >JS插入節點的方法appendChild、insertBefore

JS插入節點的方法appendChild、insertBefore

html

	<div style="background:gray"> <input type="button" value="插入節點" id="createEle" ></div>
		<div id="div2" style="background:red">
			<p id="1">1</p>
			<p>2</p>
			<p>3</p>   
			
		</div>

js

function insert(){
var div2 =document.getElementById("div2");
var newNode =document.createElement("div");
newNode.innerText="插入div2";
//div2.appendChild(newNode);//在父節點(id為div2的元素)中的子節點的末尾新增新的元素(相對於父節點來說)注:是 父子層級
//div2.insertBefore(newNode,null);//和appendChild(newNode) 效果一樣

var p1 =document.getElementById("1");
//在同一級別的節點中
//previousSibling 表示 p1節點的上一個節點
//nextSibling 表示 p1節點的下一個節點,即某個元素之後緊跟的元素(處於同一樹層級中)。
div2.insertBefore(newNode,p1.nextSibling.nextSibling.previousSibling);//在p1節點的下一個節點的下一個節點的上一個節點插入節點


//總結:由於可見insertBefore()方法的特性是:
//在已有的子節點前面插入新的節點但是兩種情況結合起來發現insertBefore()方法插入節點,
//是可以在子節點列表的任意位置。

}