Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Map html element to json object [closed]

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?

like image 811
Janith ashen Avatar asked Mar 26 '26 18:03

Janith ashen


1 Answers

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>
like image 79
Harun Yilmaz Avatar answered Mar 29 '26 06:03

Harun Yilmaz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!