Skip to content

Instantly share code, notes, and snippets.

@iwfan
Last active December 14, 2018 09:00
Show Gist options
  • Save iwfan/cbcda97d77520d1e6abdd86e0e76decd to your computer and use it in GitHub Desktop.
Save iwfan/cbcda97d77520d1e6abdd86e0e76decd to your computer and use it in GitHub Desktop.
getElementByClassName
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