使用原生JavaScript模拟getElementByClassName .

最近在工作中,由于有一个插件必须使用jquery-pack.js,而这个包又是非常古老的jquery,所以又的函数是无法使用的,例如$()选择器以及parent()都取不到标签的内容。

所以没办法,只能用原生的JavaScript了,为了实现这个功能,我得通过HTML标签的Class来获得标签的DOM结构。

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

可是在设计网页时,最常常需要使用到的class却没有相对应的方法可以去获取className相同的元素。

不过我们可以自己写一个,代码以很简单:

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跟传进来的参数进行对比,如果相等就放入数组中最后返回。

posted @ 2016-05-26 12:37  有梦就能实现  阅读(3397)  评论(0编辑  收藏  举报