Created
October 16, 2017 04:11
-
-
Save rohit012/26be0d1ef25c706a7277547bd2713842 to your computer and use it in GitHub Desktop.
GetElementByAttr
This file contains 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
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