Skip to content

Instantly share code, notes, and snippets.

@rohit012
Created October 16, 2017 04:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rohit012/26be0d1ef25c706a7277547bd2713842 to your computer and use it in GitHub Desktop.
Save rohit012/26be0d1ef25c706a7277547bd2713842 to your computer and use it in GitHub Desktop.
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