Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
GetElementByAttr
var traverseDOM = function(node, fn) {
fn(node);
node = node.firstChild;
while(node) {
traverseDOM(node, fn);
node = node.nextSibling;
}
}
var getElementByAttr = function(attr, val) {
var result = [];
traverseDOM(document.body, function(node){
var valid = node.nodeType===1 && node.getAttribute(attr);
if(typeof valid === 'string' &&(valid===val || typeof val !== 'string')) {
result.push(node);
}
});
return result;
};
console.log(getElementByAttr('class', 'test'));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.