0

I've encountered an issue when using DOMParser API. I noticed that it parses the <p> tag incorrectly.

var myHtml = '<p><span><div>Hello</div></span><div>World</div></p>'
const parsed = new DOMParser().parseFromString(myHtml, 'text/html');

// parsed is:
<html>
<head></head>
<body>
  <p></p>
  <span><div>Hello</div></span>
  <div>World</div>
  <p></p>
</body>
</html>

As you can see, there's something wrong with the structure. If you switch <p> tag with e.g. <span> it'll work just fine. What's the issue here? Is there a specific case in the spec for parseFromString method that is the reason?

Tomasz Kasperek
  • 1,147
  • 3
  • 13
  • 35
  • 1
    Paragraphs can not contain block level elements, so the parser closes the paragraph before the first div. From the [docs](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/p): *'Paragraphs are block-level elements, and notably will automatically close if another block-level element is parsed before the closing tag.'* – pilchard Mar 24 '21 at 10:50
  • @Seblor yep. It does. As well as the first comment to this post (from @pilchard). – Tomasz Kasperek Mar 25 '21 at 13:20

0 Answers0