vrintle
vrintle

Reputation: 5596

Get all HTML content from DOMParser, excluding the outer body tag

I'm using DOMParser in the following code.

let doc = new DOMParser().parseFromString('<b>sample text</b> <i>sample text</i>', 'text/html');
document.querySelector('.js').append(doc.body);
<span><b>sample text</b> <i>sample text</i></span>
<span><b>sample text</b> <i>sample text</i></span>
<span class='js'></span>

When I run it, it gives the HTML content properly, but the issue is that the outer body tag is also included in the result, which makes the content to have block display. Actually, I need to preserve the inline display, as seen in previous two spans.

I thought it's because of doc.body statement, so I tried to change it to doc.body.firstChild (which returns only b element) and doc.body.children (which returns [Object HTMLCollection]), but none of them worked.

How to fix it?


Note: <span><b>sample text</b> <i>sample text</i></span> is a dynamic content on my webpage.

Upvotes: 0

Views: 2068

Answers (2)

matek997
matek997

Reputation: 351

Try doing

document.querySelector('.js').append(...doc.body.children);

let doc = new DOMParser().parseFromString('<b>sample text</b> <i>sample text</i>', 'text/html');
document.querySelector('.js').append(...doc.body.children);
<span><b>sample text</b> <i>sample text</i></span>
<span><b>sample text</b> <i>sample text</i></span>
<span class='js'></span>

Upvotes: 3

Thiyagarajan Angappan
Thiyagarajan Angappan

Reputation: 11

I hope that my understanding is right! You are trying to display the content similar to the previous span tags. Assigning string value to the innerHTML content could help, in which case there is no need to use the DOMParser. Probably use innerHTML way to preserve inline style.

const htmlContent = '<b>sample text</b>'
document.querySelector('.js').innerHTML = htmlContent;

If there is still a requirement to use DOMParser, then you could probably do

document.querySelector('.js').innerHTML = doc.body.innerHTML

Hope it helps!

Upvotes: 1

Related Questions