Building HTML with JavaScript is important in this day and age, where AJAX is extremely popular and many Internet users have grown used to near-instant UI changes. Let’s take a look at some of the ways that developers construct HTML with JavaScript (without using some sort of template library, because lets face it, if you’re using a templating library, you’re probably not interested in this topic).
Often, developers will create one big string by concatenating HTML inside of a loop. Kind of like the code shown in this example:
var html = ""; $.each(results, function(key, val){ html += '<div class="post">'; html += '<h1>' + val.title + '</h1>'; html += '<p class="desc">' + val.summary + '</p>'; html += '<p class="date">' + val.date + '</p>'; html += '</div>'; });
As you can see, each iteration will add more and more HTML to the string.
However, there are other ways to do this. For example, you could “push” strings of HTML onto the end of an array:
var html = new Array; $.each(results, function(key, val){ html.push('<div class="post">'); html.push('<h1>' + val.title + '</h1>'); html.push('<p class="desc">' + val.summary + '</p>'); html.push('<p class="date">' + val.date + '</p>'); html.push('</div>'); }); $('#posts').html( html.join('') );
As you can see, we can use the join function when we’re ready to turn our JavaScript array into a string. By providing the join function with a blank string, the array elements are “glued” together without any spaces. From what I’ve read, this approach can be considerably faster than the string concatenation approach shown in the first example (according to several posters on StackOverflow, certain versions of Internet Explorer can be extremely sluggish when it comes to heavy string concatenation – take from that what you will because I haven’t done any benchmarks of my own).
Another approach is to create the HTML elements and then “fill in the blanks”, so to speak. i.e. We create our HTML and then fill in the data using JavaScript:
<style> /* hide the summary div by default */ #summary{display:none;} </style> <!-- our html, which is hidden by default --> <div id="summary"> <h1 id="summary-heading"></h1> <p id="summary-description"></p> </div>
If you look at the code above, you’ll see that we created our HTML and that we set the parent div #summary to display:none; This means that the summary content will remain hidden until we decide to display it. Now for the JavaScript:
//Fill in our content. $('#summary-heading').text( val.title ); $('#summary-description').text( val.desciption ); //Fade the summary in, using some fancy JQuery :) $('#summary').fadeIn( 'slow' );
As you can see, we simply filled in the content before displaying the parent div.
If you have a different way of creating HTML with JavaScript, be sure to leave a comment below.