Created
April 4, 2012 08:04
-
-
Save eikes/2299607 to your computer and use it in GitHub Desktop.
Polyfill for getElementsByClassName
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.