Last active
December 14, 2018 09:00
-
-
Save iwfan/cbcda97d77520d1e6abdd86e0e76decd to your computer and use it in GitHub Desktop.
getElementByClassName
This file contains hidden or 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 isArray(target) { | |
return Object.prototype.toString.call(target) === "[object Array]"; | |
} | |
function isClassSelector(selector) { | |
return /^\.[\w-]+$/.test(selector); | |
} | |
function getSelector(array) { | |
if (!array || !array.length) return; | |
var selectors = []; | |
array.forEach(function(item) { | |
if (typeof item === "string") { | |
if (isClassSelector(item)) { | |
selectors.push(item); | |
} | |
} else if (isArray(item)) { | |
[].forEach.call(item, function(sel) { | |
if (isClassSelector(sel)) { | |
selectors.push(sel); | |
} | |
}); | |
} | |
}); | |
return selectors; | |
} | |
function recursive(node, selector, result) { | |
if (node.nodeType === Node.ELEMENT_NODE) { | |
var classNames = node.className.split(" "); | |
if (classNames && classNames.length) { | |
for (var i = 0; i < classNames.length; i++) { | |
var cn = classNames[i]; | |
if (selector.indexOf("." + cn) !== -1) { | |
result.push(node); | |
break; | |
} | |
} | |
} | |
if (node.children && node.children.length) { | |
[].forEach.call(node.children, function(node) { | |
recursive(node, selector, result); | |
}); | |
} | |
} | |
} | |
function getElementByClassName() { | |
var selectors = getSelector([].slice.call(arguments)); | |
if (!selectors || !selectors.length) return; | |
var result = []; | |
var rootNode = document.documentElement; | |
recursive(rootNode, selectors, result); | |
return result; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment