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

javascript模拟getElementByClassName

2015-09-23 19:39 736 查看
在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跟传进来的参数进行对比,如果相等就放入数组中最后返回。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: