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?

2
  • 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. Commented Jun 19, 2012 at 12:20
  • @downvoter: Seriously? It's a good question. Upvoting to counteract. Commented Jun 19, 2012 at 12:28

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Yepper, this is most likely it.
Thats it, try it directly; document.body.innerHTML = x; alert (document.body.innerHTML)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.