Monday, 15 August 2011

javascript - How can I get the contents of a div correctly? -



javascript - How can I get the contents of a div correctly? -

below div html-code:

<div id="mydiv" contenteditable="true"> <p>this first p</p> <p id="mypid"> <ol> <li>text 1</li> <li>text 2</li> </ol> </p> </div>

during run-time need html-code. in div, correct! below give me wrong result demo:

var myhtml = $('#mydiv').html(); alert( myhtml );

the resulte of follows:

<p>this first p</p> <p id="mypid"> </p><ol> <li>text 1</li> <li>text 2</li> </ol> <p></p>

look closely, that's not previous code in div , "p" missing. idea? thanks.

this not related jquery, it's not bug, p elements can't have ol or ul child. p element can have phrasing content. browser closes p element when comes ol element.

innerhtml string representation of parsed html content of elements. form elements have defaultvalue (textarea, input[type=text], ...), defaultchecked (input[type=checkbox]) , other similar properties storing of form related values, not case other elements, i.e. there no defaultinnerhtml or similar properties.

one possible solution getting element's content via ajax, have original html instead of parsed one. note after parsing (by setting innerhtml) have same result.

$.ajax({ url: '/path/to/a/resource', }).done(function(originalhtmlreturnedbytherequest) { // });

another hackish method using script tag unknown type attribute or hidden input. using type attribute unknown browser, interpreting of script tag prevented:

<script id="originalhtml" type='whatever'> <p>this first p</p> <p id="mypid"> <ol> <li>text 1</li> <li>text 2</li> </ol> </p> </script>

javascript:

var defaultcontent = $('#originalhtml').html();

javascript jquery html

No comments:

Post a Comment