JS中對擷取一個標籤的class的方法封一個庫

來源:互聯網
上載者:User

標籤:ted   ++   creat   無法   限制   pre   i++   name   ie6   

在JS中我們經常會會用到,擷取一個標籤的id

var aId=document.getElementById("id")

現在雖然有getElementsByClassName這個方法,但是這個方法再ie6下相容性存在問題,所以保險起見還是封一個擷取class的庫

首先先看庫

/** * Created by asus on 2016/12/4 By dirk_jian. */function getByclass(oParent,sClass){    var aEle=oParent.getElementsByTagName(‘*‘);    var aResult=[];    var re=new RegExp(‘\\b‘+sClass+‘\\b‘,‘i‘);    for(var i=0;i<aEle.length;i++){//            if(aEle[i].className==sClass)             //如果有多個class那就無法檢測了//            if(aEle[i].className.search(sClass)!=-1)  //!=-1證明其有sCalss,但是只是有class這幾個字母就行,無法全面達到目的        if(re.test(aEle[i].className))                //這個就是不限制範圍的檢測        {              aResult.push(aEle[i]);        }    }    return aResult;}

再看如何調用並對擷取到的class的標籤進行css樣式的修改

 <script src="getByclass.js"></script>    <script>        window.onload=function(){            oUl=document.getElementById("div1");            var aDiv1=getByclass(oUl,‘div2‘);            var aDiv2=getByclass(oUl,‘div3‘);            for(var i=0;i<aDiv1.length;i++){                aDiv1[i].style.border=‘1px solid black‘;                aDiv1[i].style.width=‘100px‘;                aDiv1[i].style.height=‘100px‘;            }            for(var i=0;i<aDiv2.length;i++){                aDiv2[i].style.width=‘100px‘;                aDiv2[i].style.height=‘100px‘;                aDiv2[i].style.border=‘1px solid pink‘;            }        }    </script>

以下為HTML

<body>    <div id="div1">        <div class="div2"></div>        <div class="div3"></div>    </div></body>

這樣就輕鬆的可以擷取一個標籤的class了。

 

JS中對擷取一個標籤的class的方法封一個庫

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.