分享大家一个javascript操作class兼容所有浏览器教程
主要学习 IE 下没有 document.getElementByClassName 方法,我们可以利用 document.all 或者 document.getElementByTagName方法
谷歌下(w3c标准)
IE7下(非w3c标准)
代码如下:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>自学php网-js学习</title> </head> <body> <div id="div_1"> 1 </div> <div id="div_2"> 2 </div> <div class="div_3" id="div_3"> 3 </div> <div class="div_3" id="div_4"> 4 </div> <script language="javascript"> function getClass(_class_obj){ var class_arr = []; if(document.getElementsByClassName){ for(i=0; i<document.getElementsByClassName(_class_obj).length; i++){ class_arr[i] = document.getElementsByClassName(_class_obj)[i]; } }else if(document.getElementsByTagName){ var all_dom = document.getElementsByTagName("*"); var oi = 0; for( i in all_dom){ if(all_dom[i].className == _class_obj){ class_arr[oi] = all_dom[i]; oi ++; } } }else{ throw new Error("No way to retrieve element!"); return false; } return class_arr; } var dom = getClass("div_3"); // //dom.style.background = "red"; console.log(dom); </script> </body> </html>