var div1 = $("<div>");
var div2 = $("<div>");
var div3 = $("<div>");
$('#container').html('').append(div1).append(div2).append(div3);
What is the best way to do this? Thanks.
var div1 = $("<div>");
var div2 = $("<div>");
var div3 = $("<div>");
$('#container').html('').append(div1).append(div2).append(div3);
What is the best way to do this? Thanks.
There is nothing wrong with what you are doing, but if you don't need references to the elements you could just as well do:
$("#container").html("<div></div><div></div><div></div>");
Edit
You could do something like below to make the statement more terse without any real benefit.
$("#container").append(div1.add([div2, div3]));
I can see no problem with your method. However, you may re-arrange your code a bit, for the sake of readability -
var div1 = $(<div>);
var div2 = $(<div>);
var div3 = $(<div>);
$('#container').html('')
.append(div1)
.append(div2)
.append(div3);
Other than than, your method is fine.
Hope that helps.
Is it better to use empty instead of html('')?
$("#container").empty().append(div1).append(div2).append(div3);
Just seems more descriptive about what's being done. I'm not sure if html('') is more performant -- if so, then use that.
I was hoping there is a way like $('#container').html(div1+div2+div3)
There is!
var div1 = "<div></div>";
var div2 = "<div></div>";
var div3 = "<div></div>";
$("#container").html(div1 + div2 + div3);
The variables are just strings, not jQuery objects so you can do that easily.
I'm not 100% what you're trying to achieve, I think if you post your requirement people will have better solutions.
Cheers,
Marko