[ javascript ] getElementsByClassName與className和getAttribute!,getelementsbyclass

來源:互聯網
上載者:User

[ javascript ] getElementsByClassName與className和getAttribute!,getelementsbyclass

對於javascript中的getElementsByClassName 在IE 6/7/8 不支援問題。

那麼需要類比出getElementsByClassName  需要採用className屬性,這裡就涉及到javascript中的getAttribute問題。

在ie 6/7 中,對於getAttribute存在Bug

需要採用className 擷取如下:

var node = document.getElementById("test");var name = node.className;

對於標準瀏覽器,則可以直接使用className 也可以使用 getAttritbute,結果一樣:

node.getAttritbute("class");

但是如果是ie 6/7 ,則getAttribute()存在問題。

所以getElementsByClassName 可以使用如下方式:

getElementsByClazzName = document.getElementsClassName ? function(name){return document.getElementsClassName(name);}:function(name){var nodes = document.getElementsByTagName("*"),result = [];for(var node in nodes){if(node.className && node.className.indexOf(name)){result.push(node);}}return result;}

這裡的實現方式比較簡單。

1:常規屬性建議使用:node.xxx。
2:自訂屬性建議使用: node.getAttribute("xxxx")。
3:當擷取的目標是 javascript 裡的關鍵字時建議使用node.getAttribute("xxx"),如label中的for。
4:當擷取的目標是保留字,如:class,請使用className代替。


javascript 中 怎用documentgetElementsByClassName 選擇全部的類

兄弟,我介意你還是用jQuery寫吧,代碼很簡單
$(".font").css("color", "blue"); 希望能幫到您,謝謝!

 
問個對於javascript中getElementsByClassName的問題

parentElement 是父節點。類型是 element,parentElement是ie專用的,ff沒有,3c 標準是使用 parentNode 屬性,調用時傳父節點對象;oElm是document對象 或類型為element的節點對象
 

聯繫我們

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