Created
May 31, 2014 16:40
-
-
Save lmartins/dda395b01ef9a4809fbe to your computer and use it in GitHub Desktop.
Get Elements by Data-Attribute
This file contains hidden or 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
| // Define a getElementsByAttribute function. It | |
| // takes an attribute name string and an optional | |
| // matching value. It calls walk_the_DOM, passing it a | |
| // function that looks for an attribute name in the | |
| // node. The matching nodes are accumulated in a | |
| // results array. | |
| var getElementsByAttribute = function (att, value) { | |
| var results = []; | |
| walkTheDom(document.body, function(node){ | |
| var actual = node.nodeType === 1 && node.getAttribute(att); | |
| if (typeof actual === 'string' && (actual === value || typeof value !== 'string')) { | |
| results.push(node); | |
| } | |
| }); | |
| return results; | |
| }; | |
| var menus = getElementsByAttribute('data-role', 'navigation'); |
This file contains hidden or 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 walkTheDom = function walk(node, func) { | |
| func(node, 'LI'); | |
| node = node.firstChild; | |
| while (node) { | |
| walk(node, func); | |
| node = node.nextSibling; | |
| } | |
| }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment