本文主要讲解DOM常用的CURD操作,appendChild(往后追加节点),insertBefore(往前追加节点),removeChild(移除节点),replaceChild(替换节点),cloneNode(克隆节点)的语法与实战应用
一、appendChild: 向元素的内部最后面增加一个节点,或者移动一个现有的节点到元素的内部最后面
用法:
someNode.appendChild( newNode )
someNode通常为元素的父节点
返回值:
返回新增加的节点
1 <input type="text" name="" id="txt"> 2 <input type="button" value="添加" id="add"> 3 <ul id="box"></ul> 4 <script> 5 var oBtn = document.querySelector("#add"); 6 var oTxt = document.querySelector("#txt"); 7 var oBox = document.querySelector("#box"); 8 oBtn.onclick = function () { 9 var oLi = document.createElement( "li" ); 10 oLi.innerHTML = oTxt.value; 11 var returnNode = oBox.appendChild( oLi ); 12 console.log( returnNode === oLi ); //true13 console.log( returnNode === oBox.lastChild );//true14 } 15 </script>
上例,把文本框的内容当做一个新节点,添加在id为box的元素的最后面,返回值returnNode就是新增加的节点,
所以 第12行和第13行的返回值为ture, lastChild表示元素的最后一个子节点
如果appendChild后面的参数是文档现有的节点,那么表示把当前节点移动到父元素的最后面
1 <input type="button" value="移动" id="btn"> 2 <ul id="box"> 3 <li><a href="javascript:;">王朝</a></li> 4 <li><a href="javascript:;">马汉</a></li> 5 <li><a href="javascript:;">张龙</a></li> 6 <li><a href="javascript:;">赵虎</a></li> 7 <li><a href="javascript:;">ghostwu</a></li> 8 </ul> 9 <script>10 var oBtn = document.getElementById("btn"); 11 var oBox = document.getElementById("box"); 12 oBtn.onclick = function () { 13 var firstChild = oBox.firstElementChild || oBox.firstChild; 14 var lastChild = oBox.lastElementChild || oBox.lastChild; 15 var returnNode = oBox.appendChild( firstChild ); 16 firstChild = oBox.firstElementChild || oBox.firstChild; 17 lastChild = oBox.lastElementChild || oBox.lastChild; 18 console.log( returnNode === firstChild ); //false19 console.log( returnNode === lastChild ); //true20 } 21 </script>
上例,每次点击按钮,把第一个节点移动到最后,所以在第18行为false, 因为移动之后,他就不是第一个节点了,而变成最后一个节点,所以第19行比较结果为true
二、insertBefore:向一个元素前面追加节点
用法:
someNode.insertBefore( newNode, referNode );
第一个参数: newNode,需要插入的节点
第二个参数: referNode, 参考节点,即:newNode会插入到这个参考节点的前面,
注意:如果第二个参数为null, 效果等同于someNode.appendChild( newNode )
返回值:
新插入的节点
1 <input type="text" id="txt"> 2 <input type="button" value="添加" id="add"> 3 <ul id="box"></ul> 4 <script> 5 var G = function ( i

