killebytes
killebytes

Reputation: 980

multiple div in .html()?

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.

Upvotes: 0

Views: 141

Answers (4)

Marko
Marko

Reputation: 72222

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

Upvotes: 0

David Hoerster
David Hoerster

Reputation: 28701

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.

Upvotes: 1

Quintin Robinson
Quintin Robinson

Reputation: 82335

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]));

Upvotes: 3

MD Sayem Ahmed
MD Sayem Ahmed

Reputation: 29166

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.

Upvotes: 1

Related Questions