2

I'm confused with $.parseHTML() function. I thought that if the source html has a single root node this function should return an array with a single DOM node (the root node) with all the content attached as children. It works that way most of the time, for example:

var nodes = $.parseHTML('<div><div>foo</div></div>');
console.debug(nodes.length); // prints 1

However if the root node is <p> then the structure of DOM nodes is lost and the HTML gets exploded to multiple disconnected nodes:

var nodes = $.parseHTML('<p><div>foo</div></p>');
console.debug(nodes.length); // prints 3

I've created a jsfiddle where you can try these cases.

It doesn't make any difference if I use $(html) or $.parseHTML(html).

What is so special about <p> ? Why is it parsed in a different way? It this a bug or a feature?

TMG
  • 2,620
  • 1
  • 17
  • 40
  • 4
    `$.parseHTML('

    foo
    ')` result in `

    fooo

    `
    – A. Wolff Mar 05 '15 at 12:51
  • [This question](http://stackoverflow.com/questions/8397852/why-p-tag-cant-contain-div-tag-inside-it) is about it, and [this one](http://stackoverflow.com/questions/10763780/putting-div-inside-p-is-adding-an-extra-p), and [this](http://stackoverflow.com/questions/5441639/how-can-i-put-div-in-p). – Regent Mar 05 '15 at 12:54

3 Answers3

5

That's because when the HTML code is parsed, it doesn't end up with a single root node.

You can't have a block element inside a paragraph, so the paragraph ends where the div element starts. Then the ending tag for the paragraph becomes a second paragraph node.

The elements that you end up with are therefore:

<p></p>
<div>foo></div>
<p></p>
Guffa
  • 687,336
  • 108
  • 737
  • 1,005
1

W3 specs clearly states:

The P element represents a paragraph. It cannot contain block-level elements (including P itself).

And to see the effect try doing inspect element on <p><div>foo</div></p>
you will see that the code fragment has been parsed to

<p></p>
<div>foo></div>
<p></p>

enter image description here

exexzian
  • 7,782
  • 6
  • 41
  • 52
0

If I understand you correctly it's because paragraph tags can't have divs inside of it. You can read more about it in this answer - https://stackoverflow.com/a/10763952/1234502

Community
  • 1
  • 1
Pankucins
  • 1,690
  • 1
  • 16
  • 25