Skip to content

Instantly share code, notes, and snippets.

@dinks
Last active December 25, 2015 10:29
Show Gist options
  • Save dinks/6962262 to your computer and use it in GitHub Desktop.
Save dinks/6962262 to your computer and use it in GitHub Desktop.
Get Elements by Clazz
var getEByClass = function (_) {
var regExp = new RegExp("\\b" + _ + "\\b", ""),
elements = [];
var clazz = function (e) {
return e.className || "";
};
var getAll = function (context) {
var c = clazz(context);
if (c !== "" && c.match(regExp)) {
elements.push(context);
}
var children = context.childNodes;
for (var o in children) {
var e = children[o];
if (e.nodeType !== Node.ELEMENT_NODE) {
continue;
}
getAll(e);
}
};
var s = document.getElementsByTagName('html')[0];
if (s) {
getAll(s);
}
return elements;
};
// Crockford
function walkTheDOM(node, func) {
func(node);
node = node.firstChild;
while (node) {
walkTheDOM(node, func);
node = node.nextSibling;
}
}
function getElementsByClassName(className) {
var results = [];
walkTheDOM(document.body, function (node) {
var a, c = node.className,
i;
if (c) {
a = c.split(' ');
for (i = 0; i < a.length; i++) {
if (a[i] === className) {
results.push(node);
break;
}
}
}
});
return results;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment