I have an html element like this,
<div class='myparent'>
<div>
<div class="pdp-product-price">
<span> 650 rupees</span>
<div class="origin-block">
<span> 1,500 rupees</span>
<span>-57%</span>
</div>
</div>
</div>
</div>
I need to create a json of this 'myparent' div.
{
"div": {
"div": {
"div": {
"span": {},
"div": {
"span": {},
"span": {}
}
}
}
}
}
Is there a way to do this in javascript?
You can use children property of HTMLElement
Then iterate over parent recursively and get subtree.
But be aware that you cannot assign two values with the same key. Therefore, you can use an index when assigning subtree like
"div": {
"span_1": {},
"span_2": {},
}
Hope the below snippet will give you a clue.
const parent = document.getElementById('parent')
const tree = {};
const getTree = (elem) => {
const subtree = {};
for(let child of elem.children){
subtree[child.tagName.toLowerCase()] = getTree(child)
}
return subtree;
}
tree[parent.tagName.toLowerCase()] = getTree(parent);
console.log(tree);
<div id="parent" class='myparent'>
<div>
<div class="pdp-product-price">
<span> 650 rupees</span>
<div class="origin-block">
<span> 1,500 rupees</span>
<span>-57%</span>
</div>
</div>
</div>
</div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With