javascript document.getElementsByClassName 与 IE 的兼容性

发布于 2024-12-04 20:11:49 字数 1667 浏览 1 评论 0原文

检索具有特定类的元素数组的最佳方法是什么?

我会使用 document.getElementsByClassName 但 IE 不支持它。

所以我尝试了 Jonathan Snook 的解决方案

function getElementsByClassName(node, classname) {
    var a = [];
    var re = new RegExp('(^| )'+classname+'( |$)');
    var els = node.getElementsByTagName("*");
    for(var i=0,j=els.length; i<j; i++)
        if(re.test(els[i].className))a.push(els[i]);
    return a;
}
var tabs = document.getElementsByClassName(document.body,'tab');

...但 IE 仍然显示:

对象不支持此属性或方法

有什么想法、更好的方法、错误修复吗?

我不想使用任何涉及 jQuery 或其他“庞大的 javascript”的解决方案。

更新:

我让它工作了!

正如 @joe 提到的,该函数不是 document 的方法。

所以工作代码如下所示:

function getElementsByClassName(node, classname) {
    var a = [];
    var re = new RegExp('(^| )'+classname+'( |$)');
    var els = node.getElementsByTagName("*");
    for(var i=0,j=els.length; i<j; i++)
        if(re.test(els[i].className))a.push(els[i]);
    return a;
}
var tabs = getElementsByClassName(document.body,'tab');


...此外如果您只需要 IE8+ 支持那么这将起作用:

if(!document.getElementsByClassName) {
    document.getElementsByClassName = function(className) {
        return this.querySelectorAll("." + className);
    };
    Element.prototype.getElementsByClassName = document.getElementsByClassName;
}

像平常一样使用它:

var tabs = document.getElementsByClassName('tab');

What is the best method to retrieve an array of elements that have a certain class?

I would use document.getElementsByClassName but IE does not support it.

So I tried Jonathan Snook's solution:

function getElementsByClassName(node, classname) {
    var a = [];
    var re = new RegExp('(^| )'+classname+'( |$)');
    var els = node.getElementsByTagName("*");
    for(var i=0,j=els.length; i<j; i++)
        if(re.test(els[i].className))a.push(els[i]);
    return a;
}
var tabs = document.getElementsByClassName(document.body,'tab');

...but IE still says:

Object doesn't support this property or method

Any ideas, better methods, bug fixes?

I would prefer not to use any solutions involving jQuery or other "bulky javascript".

Update:

I got it to work!

As @joe mentioned the function is not a method of document.

So the working code would look like this:

function getElementsByClassName(node, classname) {
    var a = [];
    var re = new RegExp('(^| )'+classname+'( |$)');
    var els = node.getElementsByTagName("*");
    for(var i=0,j=els.length; i<j; i++)
        if(re.test(els[i].className))a.push(els[i]);
    return a;
}
var tabs = getElementsByClassName(document.body,'tab');

...Also if you only need IE8+ support then this will work:

if(!document.getElementsByClassName) {
    document.getElementsByClassName = function(className) {
        return this.querySelectorAll("." + className);
    };
    Element.prototype.getElementsByClassName = document.getElementsByClassName;
}

Use it just like normal:

var tabs = document.getElementsByClassName('tab');

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

同尘 2024-12-11 20:11:49

这不是文档的方法:

function getElementsByClassName(node, classname) {
    var a = [];
    var re = new RegExp('(^| )'+classname+'( |$)');
    var els = node.getElementsByTagName("*");
    for(var i=0,j=els.length; i<j; i++)
        if(re.test(els[i].className))a.push(els[i]);
    return a;
}

tabs = getElementsByClassName(document.body,'tab');  // no document

It's not a method of document:

function getElementsByClassName(node, classname) {
    var a = [];
    var re = new RegExp('(^| )'+classname+'( |$)');
    var els = node.getElementsByTagName("*");
    for(var i=0,j=els.length; i<j; i++)
        if(re.test(els[i].className))a.push(els[i]);
    return a;
}

tabs = getElementsByClassName(document.body,'tab');  // no document
你列表最软的妹 2024-12-11 20:11:49

您可以为旧版浏览器创建该功能

if (typeof document.getElementsByClassName!='function') {
    document.getElementsByClassName = function() {
        var elms = document.getElementsByTagName('*');
        var ei = new Array();
        for (i=0;i<elms.length;i++) {
            if (elms[i].getAttribute('class')) {
                ecl = elms[i].getAttribute('class').split(' ');
                for (j=0;j<ecl.length;j++) {
                    if (ecl[j].toLowerCase() == arguments[0].toLowerCase()) {
                        ei.push(elms[i]);
                    }
                }
            } else if (elms[i].className) {
                ecl = elms[i].className.split(' ');
                for (j=0;j<ecl.length;j++) {
                    if (ecl[j].toLowerCase() == arguments[0].toLowerCase()) {
                        ei.push(elms[i]);
                    }
                }
            }
        }
        return ei;
    }
}

you may create the function for older browsers

if (typeof document.getElementsByClassName!='function') {
    document.getElementsByClassName = function() {
        var elms = document.getElementsByTagName('*');
        var ei = new Array();
        for (i=0;i<elms.length;i++) {
            if (elms[i].getAttribute('class')) {
                ecl = elms[i].getAttribute('class').split(' ');
                for (j=0;j<ecl.length;j++) {
                    if (ecl[j].toLowerCase() == arguments[0].toLowerCase()) {
                        ei.push(elms[i]);
                    }
                }
            } else if (elms[i].className) {
                ecl = elms[i].className.split(' ');
                for (j=0;j<ecl.length;j++) {
                    if (ecl[j].toLowerCase() == arguments[0].toLowerCase()) {
                        ei.push(elms[i]);
                    }
                }
            }
        }
        return ei;
    }
}
带刺的爱情 2024-12-11 20:11:49
function getElementsByClassName(className) {
if (document.getElementsByClassName) { 
  return document.getElementsByClassName(className); }
else { return document.querySelectorAll('.' + className); } }

很确定这与 Leonid 的函数相同,但它尽可能使用 document.getElementsByClassName

function getElementsByClassName(className) {
if (document.getElementsByClassName) { 
  return document.getElementsByClassName(className); }
else { return document.querySelectorAll('.' + className); } }

Pretty sure this is the same as Leonid's function but this uses document.getElementsByClassName when it can.

兰花执着 2024-12-11 20:11:49

您无法真正复制 getElementsByClassName,因为它返回一个 nodeList,
因此它的值是实时的,并随文档更新。

您可以返回共享相同类名的元素的静态数组 -
但它不会“知道”文档何时更改。

(不需要太多这样的东西就可以使库看起来更简洁...)

function getArrayByClassNames(classes, pa){
    if(!pa) pa= document;
    var C= [], G;
    if(pa.getElementsByClassName){
        G= pa.getElementsByClassName(classes);
        for(var i= 0, L= G.length; i<L; i++){
            C[i]= G[i];
        }
    }
    else{
        classes= classes.split(/\s+/);
        var who, cL= classes.length,
        cn, G= pa.getElementsByTagName('*'), L= G.length;
        for(var i= 0; i<cL; i++){
            classes[i]= RegExp('\\b'+classes[i]+'\\b');
        }
        classnameLoop:
        while(L){
            who= G[--L];
            cn= who.className;
            if(cn){
                for(var i= 0; i<cL; i++){
                    if(classes[i].test(cn)== false) {
                        continue classnameLoop;
                    }
                }
                C.push(who);
            }
        }
    }
    return C;
}

//Example

var A= getArrayByClassNames('sideBar local')

You can't really replicate getElementsByClassName, because it returns a nodeList,
and so its value is live, and updates with the document.

You can return a static Array of elements who share the same classnames-
but it won't 'know'when the document changes.

(It won't take too many of these kind of things to make a library look svelte...)

function getArrayByClassNames(classes, pa){
    if(!pa) pa= document;
    var C= [], G;
    if(pa.getElementsByClassName){
        G= pa.getElementsByClassName(classes);
        for(var i= 0, L= G.length; i<L; i++){
            C[i]= G[i];
        }
    }
    else{
        classes= classes.split(/\s+/);
        var who, cL= classes.length,
        cn, G= pa.getElementsByTagName('*'), L= G.length;
        for(var i= 0; i<cL; i++){
            classes[i]= RegExp('\\b'+classes[i]+'\\b');
        }
        classnameLoop:
        while(L){
            who= G[--L];
            cn= who.className;
            if(cn){
                for(var i= 0; i<cL; i++){
                    if(classes[i].test(cn)== false) {
                        continue classnameLoop;
                    }
                }
                C.push(who);
            }
        }
    }
    return C;
}

//Example

var A= getArrayByClassNames('sideBar local')

笛声青案梦长安 2024-12-11 20:11:49

IE8:

document.getElementsByClassName = function (className) {
    return document.querySelectorAll('.' + className)
}

IE8:

document.getElementsByClassName = function (className) {
    return document.querySelectorAll('.' + className)
}
寄意 2024-12-11 20:11:49
function _getClass(whatEverClasNameYouWant){
var a=document.getElementsByTagName('*');
   for(b in a){
      if((' '+a[b].className+' ').indexOf(' '+whatEverClasNameYouWant+' ')>-1){
      return a[b];
      }
   }
}
function _getClass(whatEverClasNameYouWant){
var a=document.getElementsByTagName('*');
   for(b in a){
      if((' '+a[b].className+' ').indexOf(' '+whatEverClasNameYouWant+' ')>-1){
      return a[b];
      }
   }
}
沩ん囻菔务 2024-12-11 20:11:49

我只是想改进 IE8 的 querySelectorAll 后备。

就像其他人回答的那样,简单的方法是将函数添加到 Element.prototype 中,

this.querySelectorAll('.' + className);

但存在一些问题:

  • 它不适用于未修剪的字符串(在开头)。
  • 它不适用于多个类。
  • 用于“奇怪”的类字符(/$* 等)。
  • 它不适 以数字开头(无效标识符)

这意味着应该有一些“修复”,例如:

"abcd"     ->  ".abcd"
"a   b cd" ->  ".a.b.cd"
"   a b  " ->  ".a.b  "
"a/b$c d"  ->  ".a\/b\$c.d"
"1234"     ->  ".\000031234"

代码:

this.querySelectorAll(className
    .replace(/(?=[^ \w])/g, '\\')   // Escape non-word characters
    .replace(/\b\d/g, '\\00003
amp;')  // Escape digits at the beginning
    .replace(/(^| +)(?!$| )/g, '.') // Add "." before classes, removing spaces
);

I just want to improve querySelectorAll fallback for IE8.

Like others answered, the simple way is adding the function to Element.prototype with

this.querySelectorAll('.' + className);

But there are some problems:

  • It doesn't work with untrimmed strings (at the beginning).
  • It doesn't work with multiple classes.
  • It doesn't work with "strange" class characters (/, $, *, etc.)
  • It doesn't work with classes which begin with a digit (invalid identifiers)

That means there should be some "fixing", for example:

"abcd"     ->  ".abcd"
"a   b cd" ->  ".a.b.cd"
"   a b  " ->  ".a.b  "
"a/b$c d"  ->  ".a\/b\$c.d"
"1234"     ->  ".\000031234"

Code:

this.querySelectorAll(className
    .replace(/(?=[^ \w])/g, '\\')   // Escape non-word characters
    .replace(/\b\d/g, '\\00003
amp;')  // Escape digits at the beginning
    .replace(/(^| +)(?!$| )/g, '.') // Add "." before classes, removing spaces
);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文