This works (tested):
function getElementsByClassName(cn, rootNode) {
if (!rootNode) {
rootNode = document;
}
for (var r=[], e=rootNode.getElementsByTagName('*'), i=e.length; i--;) {
if ((' '+e[i].className+' ').indexOf(' '+cn+' ')>-1) {
r.push(e[i]);
}
}
return r;
}
You could probably get away with adding it to Node.prototype
, like this:
Node.prototype.getElementsByClassName = function(cn) {
for (var r=[], e=this.getElementsByTagName('*'), i=e.length; i--;) {
if ((' '+e[i].className+' ').indexOf(' '+cn+' ')>-1) {
r.push(e[i]);
}
}
return r;
}
That should add it to browsers that don't have it, but it should be shadowed by browsers that do have it since they provide it farther down the prototype chain (not tested).
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…