2

I just wanted to know the differences between the methods of adding html in jquery. both will do samething right?

$('body').append($("<div><img src='somesource' alt='something'></div>"));

and

var div = $("<div>");
var img = $("<img>").attr({"src" : "somesource", "alt" : "something"});
div.append(img);
$('body').append(div);

which is the best practice to follow?

Shreedhar
  • 5,502
  • 3
  • 22
  • 27

7 Answers7

2

The second is better. Because you often see people doing this:

var alt = 'This is " the title containing a double quote';
$('body').append($('<div><img src="somesource" alt="' + alt + '"></div>'));

and then wonder why something got eaten :-). Whereas when you use the second you have absolutely nothing to worry about:

var alt = 'This is " the title containing a double quote';
var div = $('<div>');
var img = $('<img>').attr({ src : 'somesource', alt : alt });
div.append(img);
$('body').append(div);

UPDATE:

I was too hasty in saying that you have nothing to worry about with the second approach. As others have already pointed out you have to worry about performance.

Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • the second method breaks too. – Christoph Jul 27 '12 at 10:35
  • @Christoph, oh no, of course that it doesn't break. The second method properly encodes the value. Did you try it? Because I did. Want me to provide with a fiddle? There you go. Broken: http://jsfiddle.net/u59y4/ Not broken: http://jsfiddle.net/zjRHS/ – Darin Dimitrov Jul 27 '12 at 10:35
  • I tried it in the fiddle, and it broke. Also my main concern would not be quotes but structure and performance of the insertion. – Christoph Jul 27 '12 at 10:37
  • There must then some issues with your fiddle. Checkout mine. – Darin Dimitrov Jul 27 '12 at 10:38
  • I like the encoding bit, that's prety neat – Jibi Abraham Jul 27 '12 at 10:40
  • @Christoph, yeah, what about it? Works perfectly fine. The alt is displayed without being truncated. – Darin Dimitrov Jul 27 '12 at 11:37
  • well, it doesn't for me - at least in chrome. Ah well, nevermind the webconsole showed the escaped quote as plain `"` so i just assumed, i didn't get escaped. My falut :-/ – Christoph Jul 27 '12 at 11:46
  • Ah, that's normal and a known issue with Google Chrome (damn I didn't expect I would ever say this sentence). It doesn't display alt text for images. Checkout this: http://jsfiddle.net/uSuKj/ No javascript, no nothing. Just a plain HTML and a broken browser :-) Try the same in FF or IE. – Darin Dimitrov Jul 27 '12 at 11:47
2

The second method looks better and there are lesser chances of error. But performance wise, the second method is slower. So if you're going to be doing a lot of appending, I would recommend going with the the first case - albeit, carefully.

Here's a small test case up on JS-Perf comparing the two methods

Jibi Abraham
  • 4,636
  • 2
  • 31
  • 60
1

Normally I would say DOM-scripting is the better option (the second approach); it's more structured, and easier to catch issues than by inserting a mass of HTML prepared as a string.

That said, there are performance concerns. Inserting loads of elements via DOM-scripting, particularly in a loop, can cause significant slowdown and there are cases where inserting as a string is much quicker.

Also, the fewer inserts you do - by whatever means - the fewer repaints/refreshes you force the browser to make. Again, these all require browser attention, so the fewer the better.

Mitya
  • 33,629
  • 9
  • 60
  • 107
1

See also my answer on When do you use DOM-based Generation vs. using strings/innerHTML/JQuery to generate DOM content?


The difference is that you have two variables pointing to the jQuery instances. You might can need them for eventListener-adding or manipulating them lateron in the code.

Also, DOM-based element generation has the advantage of automatically escaping the strings, which is especially useful when designing functions with parameters and absolutely needed for user input.

Therefore, the second method is most often preferred. You can also nest the appending process to make the structure clear (OK, in this example the one-liner would be clear as well):

var div = $("<div>");
var img = $("<img>", {"src":"somesource", "alt":"something"});
$('body').append(
  div.append(
    img
  )
);
Community
  • 1
  • 1
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
1

I believe you are better off using template libraries for inserting objects. An example of one such library is here: http://api.jquery.com/category/plugins/templates/

Those libraries are build for performance and ease the burden on parsing HTML blobs.

Dessus
  • 2,147
  • 1
  • 14
  • 24
1

Adding a string of HTML content is about 10 times faster

than using second method

Here is a reference

jwchang
  • 10,584
  • 15
  • 58
  • 89
  • You shoul've read the article carefully: That factor is only for repeatedly invocation of append against building a large html string. Usually, you don't need to worry whether its 1ms or 3ms. – Bergi Jul 27 '12 at 10:55
0

I would prefer the second one as the first one could lead to very long lines and if you need to bind events to certain elements you already have a variable that is pointing to it.

Pascal
  • 1,249
  • 1
  • 10
  • 21