Skip to content

Instantly share code, notes, and snippets.

@Montoya
Forked from stereobooster/function.js
Last active November 1, 2018 00:42
Show Gist options
  • Save Montoya/4225468d4ed3a39632fcf67846e5741c to your computer and use it in GitHub Desktop.
Save Montoya/4225468d4ed3a39632fcf67846e5741c 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";
if (!document.getElementsByClassName) {
document.getElementsByClassName = function (match) {
var result = [],
elements = document.body.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));
@Montoya
Copy link
Author

Montoya commented Nov 1, 2018

Couple improvements:

  • Run the polyfill when the function is not found on the document
  • Only get tags that are children of the body, rather than getting all tags in the document, since only the body and its children should have classnames (tradeoff here is this doesn't include the body element itself, but I'm ok with that)

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