Skip to content

Instantly share code, notes, and snippets.

@stereobooster
Created April 16, 2012 10:56
Show Gist options
  • Save stereobooster/2397759 to your computer and use it in GitHub Desktop.
Save stereobooster/2397759 to your computer and use it in GitHub Desktop.
getElementsByClassName polyfill
/*jshint forin:true, noarg:true, noempty:true, eqeqeq:true, bitwise:true, strict:true, undef:true, curly:true, browser:true, indent:2, maxerr:50 */
(function (document) {
"use strict";
function getElementsByClassName(match, tag) {
if (document.getElementsByClassName) {
return document.getElementsByClassName(match);
}
var result = [],
elements = document.getElementsByTagName(tag || '*'),
i, elem;
match = " " + match + " ";
for (i = 0; i < elements.length; i++) {
elem = elements[i];
if ((" " + (elem.className || elem.getAttribute("class")) + " ").indexOf(match) > -1) {
result.push(elem);
}
}
return result;
}
}(document));
/*jshint forin:true, noarg:true, noempty:true, eqeqeq:true, bitwise:true, strict:true, undef:true, curly:true, browser:true, indent:2, maxerr:50 */
(function (document) {
"use strict";
if (document.getElementsByClassName) {
document.getElementsByClassName = function (match) {
var result = [],
elements = document.getElementsByTagName('*'),
i, elem;
match = " " + match + " ";
for (i = 0; i < elements.length; i++) {
elem = elements[i];
if ((" " + (elem.className || elem.getAttribute("class")) + " ").indexOf(match) > -1) {
result.push(elem);
}
}
return result;
};
}
}(document));
@mathiasbynens
Copy link

The updated code still has the problem I described, e.g. document.getElementsByClassName('oba') would match elements with class="foobarbaz".

"" + ("this is the value of the class attribute").indexOf("ass") > -1; // true

@stereobooster
Copy link
Author

now i get it why there were those spaces

fixed

match = " " + match + " ";

@baamenabar
Copy link

In the polifill.js
Shouldn't the third line be
if (!document.getElementsByClassName) {
instead of
if (document.getElementsByClassName) {

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