javascript模拟getElementByClassName

来源:互联网 发布:锤子bigbang软件 编辑:程序博客网 时间:2024/05/18 20:06

在JavaScript 内建的核心中,document对象及element对象总共可以通过三个方式来获取其下的元素,分别是:getElementById(‘id’) 、getElementsByName(‘name’) 、getElementsByTagName(‘tag’)  。

       function getElementsByClassName(tagName,className) {              var tag = document.getElementsByTagName(tagName);              var tagAll = [];              for(var i = 0 ; i<tag.length ; i++){                  if(tag[i].className.indexOf(className) != -1){                      tagAll[tagAll.length] = tag[i];                  }              }                    return tagAll;                }  

原理就是通过获取指定的标签,使用getElementsByTagName来获取标签的内容,然后根据标签的className跟传进来的参数进行对比,如果相等就放入数组中最后返回。

0 0