JS擷取標籤方法及相容處理

來源:互聯網
上載者:User

標籤:style   blog   color   使用   io   strong   for   ar   

  1. document.getElementById(‘Id名‘);              // 所有瀏覽器
  2. document.getElementsByTagName(‘標籤名‘);        // 所有瀏覽器
  3. document.getElementsByName(‘name‘);          // 所有瀏覽器
  4. document.getElementsByClassName(‘類名‘);            // 除ie9以下,均支援

 

如需通過類名擷取標籤,併兼容所有瀏覽器,則需做相容處理:

 1 /* 2  * 功能: 通過類名擷取一定範圍內的標籤數組 3  * 參數: 第一個參數表示擷取的範圍,若在整個文檔搜尋,則傳入document; 第二個參數表示想要擷取標籤的類名 4  * 傳回值: 第一個參數裡的類名為第二個參數的標籤數組 5  */ 6 function getElementsByClass(element, classStr) { 7  8     if(element.getElementsByClassName) {    // 如果瀏覽器有getElementsByClassName的方法,則直接使用 9         return element.getElementsByClassName(classStr);    10     } else {                // 否則先尋找標籤中類名為className的標籤11 12         var elements = element.getElementsByTagName(‘*‘),13             arr = [],        // 存放類名為className的標籤14             len = elements.length;15 16         for (var i = 0; i < len; i++) {17 18             if (elements[i].className == classStr) {    // 如果為所給類名,則放入數組19                 arr.push(elements[i]);20             }21         };22 23         return arr;24     }25 }

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.