I'm successfully parsing HTML from a string using DOMParser but the output is not what I want.

This is the HTML Example I Have

codesandbox url

const html = ` <h1>Lorem ipsum head 1</h1> <p>Lorem ipsum paragraph 2</p> <p>Lorem ipsum paragraph 3</p> <img src="http://www.exampleimage.com" /> <p>Lorem ipsum paragraph 4</p> <p>Lorem ipsum paragraph 5</p> <video src="http://www.examplevideo.com"></video> <h1>Lorem ipsum head 6</h1> `; const parser = new DOMParser(); const DOM = parser.parseFromString(html, "text/html"); const body = DOM.querySelector("body"); const json = Array.from(body.children).map((element, i) => { if (element.tagName === "IMG") { return { type: "image", source: element.src }; } if (element.tagName === "VIDEO") { return { type: "video", source: element.src }; } return { type: "text", source: `<${element.tagName.toLowerCase()}>${ element.innerText }</${element.tagName.toLowerCase()}>` }; }); console.log(json);

HTML Input

<h1>Lorem ipsum head 1</h1> <p>Lorem ipsum paragraph 2</p> <p>Lorem ipsum paragraph 3</p> <img src="http://www.exampleimage.com" /> <p>Lorem ipsum paragraph 4</p> <p>Lorem ipsum paragraph 5</p> <video src="http://www.examplevideo.com"></video> <h1>Lorem ipsum head 6</h1>

The final output based on this HTML I was trying to achieve is this

// [ // { // 'type': 'text', // 'source': '<h1>Lorem ipsum head 1</h1><p>Lorem ipsum paragraph 2</p><p>Lorem ipsum paragraph 3</p>' // }, // { // 'type': 'image', // 'source': 'https://example.com/mJet2.jpg' // }, // { // 'type': 'text', // 'source': '<p>Lorem ipsum paragraph 4</p><p>Lorem ipsum paragraph 5</p>' // }, // { // 'type': 'video', // 'source': '<video src="http://www.examplevideo.com" />' // } // ]

But the output I'm getting is for every tag I'm getting the object { type: 'text', source: '' } , but I want to group text tags h1, p, p if they come in order and when it hit <img /> or <video /> in that order I want those to be object like { type: 'image', source: 'url of img' } and continue in that order. So basicly I want to keep order as represented in that HTML, but keep grouping HTML texts in one object as it showed in this above example.

If someone can help me with logic would be great because I can not figure this out