众所周知,JS获取DOM有个getElementsByClassName,非常方便,但是呢,为了兼容某些浏览器(你懂的)。只能 进行封装下了。解决方法如下
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>getElementsByClassName 封装</title> </head> <body> <div class="item">item1</div> <div class="item">item2</div> <div class="item">item3</div> <div class="item">item4</div> <div class="item">item5</div> <div class="item">item6</div> </body> <script> function getElementsByClassName(name, attrbuteName) { var arr = []; if (document.getElementsByClassName) { // 如果支持这个属性,直接获取 arr = document.getElementsByClassName(name) } else { // 如果 不支持 var attr = attrbuteName ? attrbuteName : "*";///如果指定标签名称则用 var tagNameArr = document.getElementsByTagName(attr); for (var index = 0; index < tagNameArr.length; index++) { var classNameArr = tagNameArr[index].className.split(" ") for (var j = 0; j < classNameArr.length; j++) { if (classNameArr[j] === name) { arr.push( tagNameArr[index]) } } } } return arr; } getElementsByClassName("item","div")[0].style.color = "red" </script> </html>
原文地址:https://www.cnblogs.com/huzhuhua/p/11106410.html
时间: 2024-10-11 20:52:12