欢迎来到代码驿站!

JavaScript代码

当前位置:首页 > 网页前端 > JavaScript代码

详解javascript appendChild()的完整功能

时间:2021-02-07 14:48:01|栏目:JavaScript代码|点击:

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 id="ul1">
   <li>1</li>
   <li>2</li>
   <li>3</li>
   <li>4</li>
  </ul>
  <input type="button" id="btn1" 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 id="ul1">
   <li>12</li>
   <li>2</li>
   <li>30</li>
   <li>22</li>
  </ul>
  <input type="button" id="btn1" value="移动">
 </body>
</html>

上一篇:JavaScript 节点操作 以及DOMDocument属性和方法

栏    目:JavaScript代码

下一篇:Js 实现表格隔行换色一例

本文标题:详解javascript appendChild()的完整功能

本文地址:http://www.codeinn.net/misctech/58538.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有