My question is pretty simple, and it may be subjective. For the most part when I am manipulating the DOM, I create HTML text and append it to an element. Sometimes, if the data is small enough, I will create elements and append those to the parent element.
$("#p").html("<p>My Paragraph</p>");
OR
$("<p/>").html("My Paragraph").appendTo("#p");
Which of these should be used and why?
jQuery has an even more elegant way to create elements:
The biggest value to creating elements is that you can save references to them, then use them however you need. No need to find them again using a
$()selector.If, on the other hand, your HTML is very simple and you don’t need to access any of those elements later on, it’s fine to use the
.html()method. And it’s slightly faster.