Created
March 22, 2012 14:00
-
-
Save murger/2158503 to your computer and use it in GitHub Desktop.
getElementsByClassName polyfill
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
/** | |
* 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