Skip to content

Instantly share code, notes, and snippets.

@murger
Created March 22, 2012 14:00
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save murger/2158503 to your computer and use it in GitHub Desktop.
Save murger/2158503 to your computer and use it in GitHub Desktop.
getElementsByClassName polyfill
/**
* This polyfill is originally a part of: http://github.com/murger/Qj/
* MIT license (http://opensource.org/licenses/mit-license.php)
* usage: getElementsByClassName.call(document, 'awesome')
*/
var getElementsByClassName = (function () {
if (typeof document.getElementsByClassName === 'function') {
return document.getElementsByClassName;
}
return function (cssClass) {
var nodes = (this === document)
? document.body.children
: this.children,
push = Array.prototype.push,
result = [],
i = 0, j = 0,
n, c,
elHasClass = function (node) {
return !!~(' ' + node.className + ' ').indexOf(' ' + cssClass + ' ');
},
hasChildren = function (node) {
return (node.children && node.children.length);
},
filterNodeByClass = function (node) {
if (elHasClass(node)) {
push.call(result, node);
}
};
while (n = nodes[i++]) {
filterNodeByClass(n);
if (hasChildren(n)) {
j = 0;
while (c = n.children[j++]) {
if (hasChildren(c)) {
push.call(nodes, c);
} else {
filterNodeByClass(c);
}
}
}
}
return result;
};
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment