Skip to content

Instantly share code, notes, and snippets.

@eikes
Created April 4, 2012 08:04
Show Gist options
  • Save eikes/2299607 to your computer and use it in GitHub Desktop.
Save eikes/2299607 to your computer and use it in GitHub Desktop.
Polyfill for getElementsByClassName
// Add a getElementsByClassName function if the browser doesn't have one
// Limitation: only works with one class name
// Copyright: Eike Send http://eike.se/nd
// License: MIT License
if (!document.getElementsByClassName) {
document.getElementsByClassName = function(search) {
var d = document, elements, pattern, i, results = [];
if (d.querySelectorAll) { // IE8
return d.querySelectorAll("." + search);
}
if (d.evaluate) { // IE6, IE7
pattern = ".//*[contains(concat(' ', @class, ' '), ' " + search + " ')]";
elements = d.evaluate(pattern, d, null, 0, null);
while ((i = elements.iterateNext())) {
results.push(i);
}
} else {
elements = d.getElementsByTagName("*");
pattern = new RegExp("(^|\\s)" + search + "(\\s|$)");
for (i = 0; i < elements.length; i++) {
if ( pattern.test(elements[i].className) ) {
results.push(elements[i]);
}
}
}
return results;
}
}
@wthit56
Copy link

wthit56 commented Jun 29, 2013

You should add this to Element.prototype; that would allow it to be used by document or any regular element, and would attach method where it should be in the browsers that natively support it.

Great code, BTW.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment