Last active
February 24, 2016 01:27
-
-
Save zeroeth/f02013b8c020b42e37cc to your computer and use it in GitHub Desktop.
Chrome inspector-like DOM ancestor printer.
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
| /* Output is: div#a > span.red > ul#c.xyz.123.hello.goodbye */ | |
| /* Can skip lower dom elements and truncate the class name list on each element */ | |
| /* Mock Duck */ | |
| var doc = {}; | |
| var a = {nodeName: "DIV", id: "a", className: ""}; | |
| var b = {nodeName: "SPAN", id: "", className: "red"}; | |
| var c = {nodeName: "UL", id: "c", className: " xyz 123 hello goodbye"}; | |
| c.parentNode = b; | |
| b.parentNode = a; | |
| a.parentNode = doc; | |
| /* Parent Printer */ | |
| var info = function(element, options) | |
| { | |
| options.class_limit = options.class_limit || 5; | |
| var formatted = element.nodeName.toLowerCase(); | |
| if(element.id.length > 0) | |
| { | |
| formatted = formatted + "#" + element.id; | |
| } | |
| if(element.className.length > 0) | |
| { | |
| /* Clean up white space */ | |
| var classList = element.className.split(" ").filter(function(name) { return name.length > 0 }); | |
| var classLimited = classList.slice(0, options.class_limit) | |
| var classCleaned = classLimited.map(function(name) { return "."+name;}) | |
| formatted = formatted + classCleaned.join(""); | |
| } | |
| return formatted; | |
| }; | |
| var parents = function(node, options) | |
| { | |
| var currentNode = node; | |
| var parents = []; | |
| while (currentNode.parentNode) | |
| { | |
| parents.push(info(currentNode, options)); | |
| currentNode = currentNode.parentNode; | |
| } | |
| return parents; | |
| }; | |
| var ancestors_print = function(node, options) | |
| { | |
| var options = typeof options !== 'undefined' ? options : {}; | |
| options.start_level = options.start_level || 0; | |
| console.log(parents(node, options).reverse().slice(options.start_level).join(" > ")); | |
| }; | |
| /* Test it */ | |
| ancestors_print(c, {start_level: 1, class_limit:3}); | |
| ancestors_print(c); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment