详解javascript appendChild()的完整功能

这篇文章主要介绍了详解javascript appendChild()的完整功能,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧

appendChild()常用功能。

平时我们用appendChild的时候,都是向父级上添加子元素

appendChild的另一个功能是,先把元素从原有父级上删掉,然后添加元素到新的父级。(移除再添加)。

代码说明

<!DOCTYPE html> <html> <head> <title>appendChild的第二种功能</title> <script> window.onload=function(){ var oUl1=document.getElementById("ul1"); var oUl2=document.getElementById("ul2"); var oBtn=document.getElementById("btn1"); oBtn.onclick=function(){ var oLi=oUl1.children[0]; oUl1.appendChild(oLi); } } </script> </head> <body> <ul> <li>1</li> <li>2</li> <li>3</li> <li>4</li> </ul> <input type="button" value="移动"> </body> </html>

用appendChild的第二种功能实现一个li按照内容大小排序

<!DOCTYPE html> <html> <head> <title>appendChild的第二种功能</title> <script> window.onload=function(){ var oUl1=document.getElementById("ul1"); var oBtn=document.getElementById("btn1"); oBtn.onclick=function(){ var aLi=oUl1.getElementsByTagName("li"); // aLi是一个元素集合,不是真正意义的数组,不能用sort方法,转成数组再用sort排序 var arr=[]; for(var i=0; i<aLi.length; i++){ arr.push(aLi[i]); } arr.sort(function(li1,li2){ var n1=parseInt(li1.innerHTML); var n2=parseInt(li2.innerHTML); return n1-n2 }); for(var j=0; j<arr.length; j++){ oUl1.appendChild(arr[j]);//当添加子元素的时候以前的元素已经被删除,所以不会出现重复元素 } } } </script> </head> <body> <ul> <li>12</li> <li>2</li> <li>30</li> <li>22</li> </ul> <input type="button" value="移动"> </body> </html>

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

您可能感兴趣的文章:

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:http://www.heiqu.com/ed7694aa8d919746713555723c5c6d84.html