Maxim Gershkovich
Maxim Gershkovich

Reputation: 47149

jQuery append() - duplicate appends

In a scenario where I am appending something like a div to the html body I have noticed that jQuery is smart enough to prevent appending the object twice.

So for example take the following code:

$("body").append("<div id=\"divDialog\" title=\"Custom Dialog\">My dialog question?</div>");
$("#divDialog").dialog();

No matter how many times I call the above method divDialog will only be created once (from what I can see).

In cases where you are not running in a tight loop is there anything wrong with allowing the append method to be called multiple times? Can this cause any problems?

I am assuming in a loop it would be something to avoid...

Upvotes: 0

Views: 2169

Answers (1)

James Skidmore
James Skidmore

Reputation: 50298

No, there's nothing wrong at all with running it next to each other. I don't have stats to back me, but from experience I can tell you that there's very little impact on performance. The exception would be if you're using it over and over again like in a loop, but you said that's not the case.

If both are equally easy, the better method would be to concatenate all of the HTML to append and do it at once.

Upvotes: 1

Related Questions