0

I'm working on a small project that needs to get all elements by className, there is obviously the HTML5 .getElementsByClassName, but I'm trying to create a little function that provides a small polyfill for it, it's just not working. any help much appreciated. Or if there is an easier way of doing this.

function getClassName(element) {
if(!document.getElementsByClassName(element)) {
    var retnode = [];
    var myclass = new RegExp('\\b'+element+'\\b');
    var elem = this.getElementsByTagName('*');
    for (var i = 0; i < elem.length; i++) {
        var classes = elem[i].className;
        if (myclass.test(classes)) retnode.push(elem[i]);
    }
    return retnode;
} else {
    document.getElementsByClassName(element);
}
} 

Then calling it like so:

document.getClassName('active'){
active.className += 'new';
}
4

1 回答 1

0

你的功能是错误的。

  • 这个名字意味着你得到的是一个类名,而不是一个元素。
  • element当您的意思是 className 时,您使用该变量
  • 检查支持是错误的
    • if(!document.getElementsByClassName) {
  • else 中缺少返回
    • return document.getElementsByClassName(element);

我会推荐 sse 从这里这里添加 polyfill

为自己获取一个 addClass 方法......类似于

function hasClass(elem,className) {
    return elem.className.match(new RegExp('(\\s|^)'+className+'(\\s|$)'));
}

function addClass(elem,className) {
    if (!hasClass(elem,cls)) elem.className += " "+className;
}

比你会做的

var elems = document.getClassName('active');
for (var i=elems.length-1; i>=0; i--) {
    addClass(elems[i],"active");
}
于 2013-01-31T16:11:28.133 回答