What is the sure way to add new items with jQuery?

advertisements

I just want to ask for an appropriate way to append new elements in jQuery. In the past, I tend to do string concatenation and then append to a div. However, sometimes my data contains special chars (like <>, %&, etc) and that obviously breaks my page. After a bit of research, I found out jQuery .text() does offer automatically encoding. And I thought that it would be safer to create jQuery objects first, and then append. My code would looks something like this:

$.each(data.items, function(index, photo) {
            var $imageSpan = $("<span></span>").addClass("image");
            var $anchorTag = $("<a></a>").prop("href", photo.link);
            $("<img/>").prop("src", photo.media.m.replace("_m", "_o")).appendTo($anchorTag);
            $anchorTag.appendTo($imageSpan);

            $photoDiv.append($imageSpan);
        });

However, this page: http://www.learningjquery.com/2009/03/43439-reasons-to-use-append-correctly points out that it is actually a horrible approach. So, is there a way to be safe (text is all encoded) and achieve greatest performance?


IMO, you're doing the right thing to make sure you don't have encoding issues. A great way to improve performance is to place the elements in an Array and only have the one call to append with that array. The main performance implications with multiple append calls is that the DOM may have to recompute the layout of the screen after each time, and that will slow everything down.

var photos = [];
$.each(data.items, function(index, photo) {
  var $imageSpan = $("<span></span>").addClass("image");
  var $anchorTag = $("<a></a>").prop("href", photo.link);
  $("<img/>").prop("src", photo.media.m.replace("_m", "_o")).appendTo($anchorTag);
  $anchorTag.appendTo($imageSpan);
  photos.push($imageSpan);
});
$photoDiv.append(photos);

I would also inline any HTML attributes which are not dynamic. For example, .addClass("image") is not very beneficial; would be faster to put that attribute inline, with $('<span class="image"></span>').