您的位置:首页 > Web前端 > JavaScript

使用原生JavaScript模拟getElementByClassName

2014-09-15 15:31 465 查看
最近在工作中,由于有一个插件必须使用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跟传进来的参数进行对比,如果相等就放入数组中最后返回。

源文出处:http://www.tonitech.com/1604.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: