javascript document.getElementsByClassName compatibility with IE

前端 未结 7 692
逝去的感伤
逝去的感伤 2020-11-22 08:44

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.

7条回答
  •  南旧
    南旧 (楼主)
    2020-11-22 09:07

    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$&')  // Escape digits at the beginning
        .replace(/(^| +)(?!$| )/g, '.') // Add "." before classes, removing spaces
    );
    

提交回复
热议问题