JS獲取標籤方法及兼容處理

  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 }
相關文章
相關標籤/搜索