这是通过扩展Element.prototype
和 的快速解决方案document
:
(function() {
if (!document.getElementsByClassName) {
var indexOf = [].indexOf || function(prop) {
for (var i = 0; i < this.length; i++) {
if (this[i] === prop) return i;
}
return -1;
};
getElementsByClassName = function(className, context) {
var elems = document.querySelectorAll ? context.querySelectorAll("." + className) : (function() {
var all = context.getElementsByTagName("*"),
elements = [],
i = 0;
for (; i < all.length; i++) {
if (all[i].className && (" " + all[i].className + " ").indexOf(" " + className + " ") > -1 && indexOf.call(elements, all[i]) === -1) elements.push(all[i]);
}
return elements;
})();
return elems;
};
document.getElementsByClassName = function(className) {
return getElementsByClassName(className, document);
};
if(Element) {
Element.prototype.getElementsByClassName = function(className) {
return getElementsByClassName(className, this);
};
}
}
})();
然而,扩展原型对象并不总是最好的主意,尤其是对于一个名称与不存在的本机函数完全一样的函数。如果你想逃避原型扩展带来的问题,使用这段代码:
(function() {
var indexOf = [].indexOf || function(prop) {
for (var i = 0; i < this.length; i++) {
if (this[i] === prop) return i;
}
return -1;
};
window.getElementsByClassName = function(className,context) {
if (context.getElementsByClassName) return context.getElementsByClassName(className);
var elems = document.querySelectorAll ? context.querySelectorAll("." + className) : (function() {
var all = context.getElementsByTagName("*"),
elements = [],
i = 0;
for (; i < all.length; i++) {
if (all[i].className && (" " + all[i].className + " ").indexOf(" " + className + " ") > -1 && indexOf.call(elements,all[i]) === -1) elements.push(all[i]);
}
return elements;
})();
return elems;
};
})();
这样,您可以安全地使用getElementsByClassName()
接受两个参数的函数:
className
: CSS 类
context
: 节点