Last active
August 29, 2015 14:02
-
-
Save mtmzorro/efac652c289d5f59acfb to your computer and use it in GitHub Desktop.
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
/** | |
* [getElementsByClassName] | |
* @param {[String]} searchClass [searchClass] | |
* @param {[Object]} node [node document] | |
* @param {[String]} tag [html tag] | |
* @return {[Array]} [result] | |
* | |
* @from http://www.cnblogs.com/rubylouvre/archive/2009/07/24/1529640.html | |
*/ | |
var getElementsByClassName = function(searchClass, node, tag) { | |
if (document.getElementsByClassName) { | |
var nodes = (node || document).getElementsByClassName(searchClass), | |
result = []; | |
for (var i = 0; node = nodes[i++];) { | |
if (tag !== "*" && node.tagName === tag.toUpperCase()) { | |
result.push(node) | |
} | |
} | |
return result | |
} else { | |
node = node || document; | |
tag = tag || "*"; | |
var classes = searchClass.split(" "), | |
elements = (tag === "*" && node.all) ? node.all : node.getElementsByTagName(tag), | |
patterns = [], | |
current, | |
match; | |
var i = classes.length; | |
while (--i >= 0) { | |
patterns.push(new RegExp("(^|\\s)" + classes[i] + "(\\s|$)")); | |
} | |
var j = elements.length; | |
while (--j >= 0) { | |
current = elements[j]; | |
match = false; | |
for (var k = 0, kl = patterns.length; k < kl; k++) { | |
match = patterns[k].test(current.className); | |
if (!match) break; | |
} | |
if (match) result.push(current); | |
} | |
return result; | |
} | |
} |
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
function getElementsByClassName(node, classname) { | |
if (node.getElementsByClassName) { // use native implementation if available | |
return node.getElementsByClassName(classname); | |
} else { | |
return (function(searchClass, node) { | |
if (node == null) | |
node = document; | |
var classElements = [], | |
els = node.getElementsByTagName("*"), | |
elsLen = els.length, | |
pattern = new RegExp("(^|\\s)" + searchClass + "(\\s|$)"), | |
i, j; | |
for (i = 0, j = 0; i < elsLen; i++) { | |
if (pattern.test(els[i].className)) { | |
classElements[j] = els[i]; | |
j++; | |
} | |
} | |
return classElements; | |
})(classname, node); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment