原生JS獲取指定元素下指定子元素(兼容所有瀏覽器)


好幾天沒有寫博客了,今天分享下JS如何獲取指定元素下指定的子元素。

原理:

由於JS內置獲取子元素節點方法(children)不兼容低版本瀏覽器(ie 6-8),通過獲取所有子節點(childNodes)方法獲取所有子節點,循環判斷取出元素子節點,存儲在數組里,循環數組判斷取出數組元素和傳遞元素相同的元素節點,具體見下面代碼。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>獲取指定元素下指定子元素children兼容寫法</title>
    <style type="text/css">
    #create{width: 500px;height: 500px;margin:50px auto;border:1px solid red;}
    p{background: blue;border-bottom: 1px solid #fff;width: 100%;height: 20px;}
    </style>
    
</head>
<body>
    <div id="create">
       <p></p>
       <p></p>
       <div></div>
       <div>
         <p></p>
         <p></p>
       </div>
       <p></p>
    </div>
    <script>
       var creat = document.getElementById("create");

       function children(curEle,tagName){
               var nodeList = curEle.childNodes;
               var ary = [];
               if(/MSIE(6|7|8)/.test(navigator.userAgent)){
                   for(var i=0;i<nodeList.length;i++){
                       var curNode = nodeList[i];
                       if(curNode.nodeType ===1){
                          ary[ary.length] = curNode;
                       }
                   }
               }else{
                   ary = Array.prototype.slice.call(curEle.children);
               }
               
               // 獲取指定子元素
               if(typeof tagName === "string"){
                   for(var k=0;k<ary.length;k++){
                     curTag = ary[k];
                     if(curTag.nodeName.toLowerCase() !== tagName.toLowerCase()){
                      ary.splice(k,1);
                      k--;
                     }
                   }
               }

               return ary;
       }
       console.log(children(create,"div"));
    </script>
</body>
</html>

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM