Created
March 16, 2016 12:48
-
-
Save ramonvictor/b21af1b26d294e7d71f6 to your computer and use it in GitHub Desktop.
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
(function() { | |
function getTreeWalker(root, onlyComponents) { | |
return document.createTreeWalker( | |
root, | |
NodeFilter.SHOW_ELEMENT, | |
{ | |
acceptNode: function(node) { | |
if (onlyComponents) { | |
if (node && node.nodeType === 1 && node.dataset.component) { | |
return NodeFilter.FILTER_ACCEPT; | |
} | |
return NodeFilter.FILTER_SKIP; | |
} else { | |
return NodeFilter.FILTER_ACCEPT; | |
} | |
} | |
}, | |
false | |
); | |
} | |
function getNodeName(node) { | |
return node.nodeName.toLowerCase(); | |
} | |
function getClassNames(node) { | |
return node.getAttribute('class'); | |
} | |
function getDataAttribute(node, data) { | |
return node.dataset[data]; | |
} | |
var output = { | |
tag: 'body', | |
children: [] | |
}; | |
function buildObjectTree(node, level) { | |
var nodeObject; | |
var index; | |
var child; | |
var currentNode; | |
var componentAttr; | |
// var TW = getTreeWalker(node, 1); // components only | |
var TW = getTreeWalker(node); | |
var nextElement = TW.firstChild(); | |
while(nextElement) { | |
currentNode = TW.currentNode; | |
componentAttr = getDataAttribute(currentNode, 'component'); | |
// Define objet structure | |
nodeObject = { | |
tag: getNodeName(currentNode), | |
class: getClassNames(currentNode), | |
component: componentAttr, | |
children: [] | |
}; | |
// Push current object | |
level.push(nodeObject); | |
// Check child level | |
if (TW.firstChild()) { | |
index = level.indexOf(nodeObject); | |
parent = TW.parentNode(); // Point back to `currentNode` | |
buildObjectTree(parent, level[index].children); | |
} | |
// Go to next sibling | |
nextElement = TW.nextSibling(); | |
} | |
} | |
buildObjectTree(document.body, output.children); | |
console.log(JSON.stringify(output, null, '\t')); | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment