When I use the jQuery append()
method, the resulting HTML output is not in the order I intend.
As you see in the test case below, any time I open a DIV
tag without closing it, it is closed nevertheless.
The same goes for the <ul>
tag - which was also closed before I expected - I wanted it to be closed after the second <li>
tag that is supposed to be nested below it.
What's the best way to build a large block of dynamic HTML in the order it is written?
$('#a').remove(); // remove #a from the dom and re-insert it dynamically
$("<div id='a'>").insertAfter('div#main');
$('#a').append(" <ul>");
$('#a').append(" <li>A</li>");
$('#a').append(" <li>B</li>");
$('#a').append(" </ul>");
$('#a').append(" <div id='X1'>");
$('#a').append(" <div id='b'>");
$('#a').append(" <div id='b1'></div>");
$('#a').append(" <div id='b2'></div>");
$('#a').append(" </div>");
$('#a').append(" <div id='c'>");
$('#a').append(" <p id='c1'></p>");
$('#a').append(" </div>");
$('#a').append(" </div>");
$('#a').append(" <div id='X2'>B</div>");
$('#a').append("</div>");
<div id="main>
<div id="a>
<ul></ul> // <ul> tag is closed!?
<li>A</li>
<li>B</li>
<div id='X1'></div> // div is closed!?
<div id='b'> // div is closed!?
<div id='b1'></div>
<div id='b2'></div>
<div id='c'></div> // div is closed!?
<p id='c1'></p>
<div id='X2'>B</div>
</div>
</div>