0
var wrapper = $('<p><div class="text">Hello World</div></p>');
console.log(wrapper.html());

Becomes

<p></p><div class="text">SOMETHING</div><p></p>

How can you avoid the HTML being messed up like that?


ANSWER : I did not realize putting a DIV inside a paragraph was invalid HTML.

Mark
  • 16,906
  • 20
  • 84
  • 117
  • 6
    It's invalid to have a div inside a p: http://stackoverflow.com/questions/4291467/nesting-block-level-elements-inside-the-p-tag-right-or-wrong . – Andrew Morton May 06 '12 at 15:27
  • 2
    *How can you avoid the HTML being messed up like that?* Create valid HTML :P The browser will always try to correct invalid HTML... – Felix Kling May 06 '12 at 15:28

3 Answers3

6

div is not supported within p

thecodeparadox
  • 86,271
  • 21
  • 138
  • 164
0

Try

var wrapper = $('<p></p>').html('<div class="text">Hello World</div>');
console.log(wrapper);
debianek
  • 589
  • 1
  • 9
  • 30
0
var wrapper = $( '<p></p>').append(
    $( '<div></div>' )
        .text( 'Hello World' )
        .attr( 'class', 'text' )
);

Or just using innerHTML from your comments:

var wrapper = document.createElement('p');
wrapper.innerHTML = '<div class="text">Hello World</div>';
console.log( wrapper );​

Jsfiddle: http://jsfiddle.net/Ralt/R9kXU/

Florian Margaine
  • 58,730
  • 15
  • 91
  • 116
  • I appreciate your reply however I am loading html content from an external source and try to add that to the DOM, but all P get messed up like that. – Mark May 06 '12 at 15:28