I have the following code:
$("#samplediv").html("<div>");
$("#samplediv").append("<b>Test text</b>");
$("#samplediv").append("</div>");
I require the following output:
<div><b>Test text</b></div>
However, the output is:
<div></div><b>Test text</b>
What am I doing wrong? How can I prevent this behaviour?
Thanks!
It is the browser doing it, not jquery. Most browsers are going to fix faultly HTML as best they can. If you add only part of a Div, it will fix it by adding the rest.
Here is some info though…
Dom queries are costly in all JS, even more so in jQuery. In yours, you are doing three. You can reduce that to one, by doing the following code:
If you build your html separate, and then do your append, you will be able to do what you want. This is the recommended way of dealing with DOM manipulation. It is way more performent.