Generating HTML code dynamically with jQuery I am doing a college project and I would like to write my jQuery code following best practices. The project involves using the jQuery .getJSON method to retrieve information from a json file. I have left out parts of the code so that it is more readable (however this is indicated in the comments).

The code shows two approaches I have come up with:


In the first approach, I define a variable which contains HTML code and inserts this dynamically when making a call to the JSON file. I then do a small amount of DOM manipulation with this.
In the second approach I don't need to define the variable at all. However, there is slightly more jQuery DOM manipulation when retrieving the information from the json file. also I'm not sure if what I have done is a bit 'hacky'.


Do you have any advice on which way would be better practice to do?

Option 1:

$(document).ready(function(){

//define a variable which contains html code that will be inserted dynamically depending on the contents of the json
        var gift_love_template =    '&lt;span class="gift love-gift"&gt;' +
                            '&lt;i class="fa fa-heart" aria-hidden="true"&gt;&lt;/i&gt;' +
                            '&lt;!--quantity of the gift will be dynamically inserted here--&gt;' +
                        '&lt;/span&gt;';

        //the following code is inside the call to the JSON file:
        $.each(profile.posts, function(i, post){
            var quantity_love = post.gifts.love;    //number of loves is stored in the gifts array within the post object.

            if(quantity_love != 0){
                var love_title = "" + quantity_love + " loves received"; //create a string for the title attribute
                $("#" + post_id + " .gift-area").append(gift_love_template);
                $("#" + post_id + " .love-gift").attr("title", love_title).append("(" + quantity_love + ")");
            }

        });
});


Option 2:

$(document).ready(function(){

    //the following code is inside the call to the JSON file:

        $.each(profile.posts, function(i, post){
            var quantity_love = post.gifts.love;    //number of loves is stored in the gifts array within the post object.

            if(quantity_love != 0){
                var love_title = "" + quantity_love + " loves received"; //create a string for the title attribute
                $('&lt;span&gt;&lt;i class="fa fa-heart" aria-hidden="true"&gt;&lt;/i&gt;(' + quantity_love + ')&lt;/span&gt;').attr("class", "gift").attr("title", love_title).appendTo("#" + post_id + " .gift-area");
            }

        });
});
I suggest you put the template html in an invisible div in the page html. 
Then reference and clone it from javascript.
Then replace "tags" with data from the json request and insert the new html in the page at the appropriate place.

You can then redesign the page without touching the javascript code.