IE 8: Object doesn't support property or method 'getElementsByClassName'

拈花ヽ惹草 提交于 2019-11-27 15:32:37

IE8 does not support getElementsByClassName. However, it does support querySelectorAll. So, I suggest to write a polyfill using querySelectorAll.

document.getElementsByClassName('foo')

turns into

document.querySelectorAll('.foo'); // Prefixed dot.

Note that Prototype.js deprecates the use of getElementsByClassName in favour of $$ and Element#select.

A quick fix for IE8:

<!--[if IE 8]><script>
document.getElementsByClassName = 
Element.prototype.getElementsByClassName = function(class_names) {
    // Turn input in a string, prefix space for later space-dot substitution
    class_names = (' ' + class_names)
        // Escape special characters
        .replace(/[~!@$%^&*()_+\-=,./';:"?><[\]{}|`#]/g, '\\$&')
        // Normalize whitespace, right-trim
        .replace(/\s*(\s|$)/g, '$1')
        // Replace spaces with dots for querySelectorAll
        .replace(/\s/g, '.');
    return this.querySelectorAll(class_names);
};
</script><![endif]-->

Notes:

  • It does support multiple class names.
  • It does not support empty ('') class names. It's trivial to add support for these, if you want.

Demo: http://jsfiddle.net/HL4FL/21/

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!