Skip to content

Instantly share code, notes, and snippets.

@greut
Created December 14, 2008 15:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save greut/35707 to your computer and use it in GitHub Desktop.
Save greut/35707 to your computer and use it in GitHub Desktop.
// Element.prototype.getElementsByClassName (using XPath or getElementsByTagName)
// Monkeypatching is evil
if(typeof Element.getElementsByClassName === "undefined") {
if("evaluate" in document) {
Element.prototype.getElementsByClassName = function(className) {
var result = document.evaluate(".//*[contains(concat(' ', @class, ' '), '"+className+"')]", this, null, XPathResult.ANY_TYPE, null),
node,
elements = [];
while(node = result.iterateNext()) {
elements.push(node);
}
return elements;
}
} else {
Element.prototype.getElementsByClassName = function(className) {
var allChilds = this.getElementsByTagName("*"),
re = new RegExp('\\b'+className+'\\b');
elements = [];
for(var i=0; i<allChilds.length; i++) {
if(~allChilds[i].className.search(re)) {
elements.push(allChilds[i]);
}
}
return elements;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment