Given some HTML, write a function to convert HTML 2 JSON
Solution
<body>
<div id="rootA" class="rootA" data-test="test" style="margin: 5px; background-color: rebeccapurple;">
<div>
<div>Hello World</div>
</div>
<div></div>
<div>
<div>
<div id="nodeA"></div>
<div></div>
</div>
</div>
</div>
<div id="rootB">
<div>
<div></div>
</div>
<div></div>
<div>
<div>
<div id="nodeB"></div>
<div></div>
</div>
</div>
</div>
<script type="text/javascript">
const rootA = document.getElementById('rootA');
const rootB = document.getElementById('rootB');
const nodeA = document.getElementById('nodeA');
const nodeB = document.getElementById('nodeB');
function getPath(root, node) {
const path = [];
while (node !== root) {
const parent = node.parentNode;
const children = Array.from(parent.children);
const nodeIndex = children.indexOf(node);
path.push(nodeIndex);
node = parent;
}
console.log(path);
return path;
}
function getNodeFromPath(node, path) {
const toWalk = [...path];
while (toWalk.length > 0) {
node = node.children[toWalk.pop()];
}
return node;
}
const getSourcePath = (root, node) => {
const path = [];
while (root !== node) {
const parent = node.parentNode;
const children = Array.from(parent.children);
const nodeIndex = children.indexOf(node);
path.push(nodeIndex);
node = parent;
}
return path;
}
const getTargetFromPath = (root, path) => {
const toWalk = [...path];
while (toWalk.length > 0) {
root = root.children[toWalk.pop()]
}
return root;
}
function getSymmetricNode(rootA, rootB, nodeA) {
const pathToNode = getSourcePath(rootA, nodeA);
return getTargetFromPath(rootB, pathToNode);
}
const targetNode = getSymmetricNode(rootA, rootB, nodeA);
console.log(nodeB === targetNode);
const htmlToJson = (div, obj) => {
if (!obj) { obj = [] }
let tag = {}
tag['tagName'] = div.tagName
tag['children'] = []
for (var i = 0; i < div.children.length; i++) {
tag['children'].push(htmlToJson(div.children[i]))
}
tag.attributes = {}
for (var i = 0; i < div.attributes.length; i++) {
var attr = div.attributes[i]
tag.attributes[attr.name] = attr.value
}
return tag
}
console.log(htmlToJson(rootA))
let root
const jsonToHtml = (domObj) => {
const ele = document.createElement(dom.obj.tagName);
}
</script>