Skip to content

Instantly share code, notes, and snippets.

@jonhoo
Created May 11, 2012 13:37
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 jonhoo/2659693 to your computer and use it in GitHub Desktop.
Save jonhoo/2659693 to your computer and use it in GitHub Desktop.
Simple polyfill for fetching all elements on the page with the given class
"getElementsByClassName"in document||(document.getElementsByClassName=document.evaluate?function(a){var a="[contains(concat(' ', @class, ' '), ' "+a+" ')]",d="http://www.w3.org/1999/xhtml"===document.documentElement.namespaceURI?"http://www.w3.org/1999/xhtml":null,b;try{b=document.evaluate(".//*"+a,document,d,0,null)}catch(c){b=document.evaluate(".//*"+a,document,null,0,null)}return b}:function(a){for(var a=RegExp("(^|\\s)"+a+"(\\s|$)"),d=document.all||document.getElementsByTagName("*"),b=[],c=0,e=
d.length;c<e;c+=1)a.test(d[c].className)&&b.push(d[c]);return b});
/*
Based on "The ultimate getElementsByClassName, anno 2008" by Robert Nyman
http://robertnyman.com/2008/05/27/the-ultimate-getelementsbyclassname-anno-2008/
Developed by Jon Gjengset <jon@thesquareplanet.com>
MIT license
This file will provide a stupidly simple fallback for getElementByClassName
Namely one that only supports lookup of a single class, and only on document
It also won't allow limiting results to only tags of a single type
Also, return types won't be normalized, so you might get an array or a NodeList depending
on the underlying implementation being used.
It is also about half the size of the Ultimate version at 1.8KB (571B minified) vs 2.4KB (1.05KB minified)
*/
if (!("getElementsByClassName" in document)) {
if (document.evaluate) {
document.getElementsByClassName = function (className) {
var classCheck = "[contains(concat(' ', @class, ' '), ' " + className + " ')]",
xhtmlNamespace = "http://www.w3.org/1999/xhtml",
namespaceResolver = (document.documentElement.namespaceURI === xhtmlNamespace)? xhtmlNamespace : null,
elements;
try {
elements = document.evaluate(".//*" + classCheck, document, namespaceResolver, 0, null);
}
catch (e) {
elements = document.evaluate(".//*" + classCheck, document, null, 0, null);
}
return elements;
};
} else {
document.getElementsByClassName = function (className) {
var classCheck = new RegExp("(^|\\s)" + className + "(\\s|$)"),
elements = document.all || document.getElementsByTagName('*'),
returnElements = [];
for (var l=0, ll=elements.length; l<ll; l+=1) {
if (classCheck.test(elements[l].className)) {
returnElements.push(elements[l]);
}
}
return returnElements;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment