Skip to content

Instantly share code, notes, and snippets.

@PantherHawk
Created November 8, 2017 22:24
Show Gist options
  • Save PantherHawk/0ec895981703168293e9281e36948d27 to your computer and use it in GitHub Desktop.
Save PantherHawk/0ec895981703168293e9281e36948d27 to your computer and use it in GitHub Desktop.
//to go into a DOM trees we use document.childNodes
// we have to make a tree structure of the DOM
// traverse the DOM, and make a new tree for every node, and print the tree
class Tree {
constructor(val) {
this.val = val;
this.children = [];
}
add(val) {
let newnode = new Tree(val);
this.children.push(newnode);
}
}
let domTree = (oldTree) => {
// make a new tree from the old one, map the tree
let sub = (oldtree, newtree) => {
oldtree.childNodes.forEach((node, i) => {
newtree.add(node.nodeName);
sub(node, newtree.children[i]);
});
};
let val = oldTree.nodeName;
let newtree = new Tree(val);
sub(oldTree, newtree);
let treeText = JSON.stringify(newtree);
return treeText;
let prettifyTree = (treeString) => {
//output: the tree, but wherever there's 'children' key, paragraph and insert
treeString.split('children').forEach(el => console.log(el));
}
prettifyTree(treeText)
// let tre = document.createElement("tree");
// document.body.append(tre);
// tre.setAttribute("class", "tree");
// document.querySelector(".tree").innerHTML = treeText;
}
domTree(document)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment