JavaScript中获取元素document.getElementsByClassName()在IE8以下不兼容
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <script> window.onload = function () { var li = document.getElementsByClassName('cla'); console.log(li); } </script> </head> <body> <div id="div1"> <ul> <li class="cla">abc</li> <li class="cla1">abc</li> <li class="cla">abc</li> <li class="cla1">abc</li> <li class="cla">abc</li> <li class="cla2">abc</li> <li class="cla">abc</li> <li class="cla1">abc</li> </ul> </div> </body> </html>
可以自己定义方法来兼容IE浏览器
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <script> window.onload = function () { /* var li = document.getElementsByClassName('cla'); console.log(li); */ var node = document.getElementById('div1'); var ele = getElementsByClassNameUserDefined(node,'cla'); for (var i = 0; i < ele.length; i++) { ele[i].style.color = 'red'; } } /* 自定义兼容ie浏览器的方法 @param node 要获取哪些元素下的class @param className 类名 */ function getElementsByClassNameUserDefined(node, className){ // 获取元素下的所有标签 var eleList = node.getElementsByTagName('*'); var arr = []; // 循环遍历所有标签,当标签的className等于传入的className时放入数组 for(var i = 0; i < eleList.length; i++) { if (eleList[i].className == className) { arr.push(eleList[i]); } } return arr; } </script> </head> <body> <div id="div1"> <ul> <li class="cla">abc</li> <li class="cla1">abc</li> <li class="cla">abc</li> <li class="cla1">abc</li> <li class="cla">abc</li> <li class="cla2">abc</li> <li class="cla">abc</li> <li class="cla1">abc</li> </ul> </div> </body> </html>
效果: