0

I found out jQuery does not always create the correct DOM from an HTML string. Here is a little example code:

var x = "<div><p><ul><li>1</li></ul></p></div>";
console.log('x = ' + x);
console.log('jQuery(x) = ' + jQuery(x).html());
var y = "<div><div><ul><li>1</li></ul></div></div>";
console.log('y = ' + y);
console.log('jQuery(y) = ' + jQuery(y).html());

Here is the output I get running this with jQuery 1.7.1:

x = <div><p><ul><li>1</li></ul></p></div>
jQuery(x) = <p></p><ul><li>1</li></ul><p></p>
y = <div><div><ul><li>1</li></ul></div></div>
jQuery(y) = <div><ul><li>1</li></ul></div>

As you can see, the second example creates the correct DOM, the first example does not. The only difference is a <p> tag instead of a <div>. Is this a bug or feature of jQuery?

wolfey
  • 13
  • 1
  • You are specifying invalid html. It is the input that is incorrect not the output. The html you see in the result is auto-corrected html. – Nope Jun 19 '12 at 12:20
  • @downvoter: Seriously? It's a good question. Upvoting to counteract. – Xyan Ewing Jun 19 '12 at 12:28

1 Answers1

8

That's probably a browser nuance, since <ul> elements are illegal in <p> elements.

What's probably happening is that, when jQuery attempts to create the HTML elements in your string as it understood it, the browser is "auto-correcting" the HTML generated as jQuery goes along.

Community
  • 1
  • 1
Richard Neil Ilagan
  • 14,627
  • 5
  • 48
  • 66