If you are using Jquery > 1.4, you are best of with Ian's answer. Otherwise, I would use this method:
This is very similar to celoron's answer, but I don't know why they used document.createElement
instead of Jquery notation.
$("body").append(function(){
return $("<div/>").html("I'm a freshly created div. I also contain some Ps!")
.attr("id","myDivId")
.addClass("myDivClass")
.css("border", "solid")
.append($("<p/>").html("I think, therefore I am."))
.append($("<p/>").html("The die is cast."))
});
//Some style, for better demonstration if you want to try it out. Don't use this approach for actual design and layout!
$("body").append($("<style/>").html("p{background-color:blue;}div{background-color:yellow;}div>p{color:white;}"));
I also think using append()
with a callback function is in this case more readable, because you now immediately that something is going to be appended to the body. But that is a matter of taste, as always when writing any code or text.
In general, use as less HTML as possible in JQuery code, since this is mostly spaghetti code. It is error prone and hard to maintain, because the HTML-String can easily contain typos. Also, it mixes a markup language (HTML) with a programming language (Javascript/Jquery), which is usually a bad Idea.