2

Javascript better practices: Clone HTML templates instead of directly creating elements

When manipulating the DOM with Javascript, try to avoid creating elements as much as possible. Instead, clone an HTML template, then use Javascript to alter the text and attributes of those elements.

The main benefit of this practice is to keep the HTML separate from the Javascript source. This way, you can style and rearrange HTML elements as much as you’d like, without having to modify your Javascript code.

For example, say we have a list of items grabbed from a feed:

<ul id="feeds">
  <li>
    <h2 class="title">Item title</h2>
    <div class="description">
      Lorem ipsum sin dolor sit amet...
    </div>
  </li>
  ...
</ul>

And say in your Javascript code (jQuery in this example), you’re dumping a feed’s items into this list:

$.get('/feed/url', function(results) {
  for (var i = 0; i < results.entries.length; i++) 
  {
    var entry = results.entry[i];
    
    var li = $('<li></li>');
    $(li).text(entry.title);
    ...
    $(li).appendTo('#feeds');
  }
});

Above, we’re using jQuery to create the <li> element. There’s really nothing wrong with this, but if you use an HTML template beforehand, you can save yourself some time in the future, when you need to make changes.

So our plan is to:

  1. Create an HTML template for the list item
  2. clone() this with jQuery
  3. Alter the attributes and text with jQuery
  4. Then append it to the <ul>

So let’s start with the HTML template:

<ul id="feeds">
  <li class="template" style="display:none">
    <h2 class="title">Item title</h2>
    <div class="description">
      Lorem ipsum sin dolor sit amet...
    </div>
  </li>
</ul>

Now we have a simple HTML template for our list item. Next, we’ll modify the Javascript to clone the list item, then modify its contents and their attributes, rather than creating elements directly.

$.get('/feed/url', function(results) {
  for (var i = 0; i < results.entries.length; i++) 
  {
    var entry = results.entry[i];
    
    // clone li.template
    var li = $('#feeds li.template').clone();
    $(li).removeAttr('style')
         .removeClass('template');
        
    // manipulate its contents
    $(li).find('.title').text(entry.title);
    $(li).find('.description').text(entry.description);
    ...
    $(li).appendTo('#feeds');
  }
});

Now you can modify the HTML, move things around, or change the elements without having to modify your Javascript. Good practice for future-proofing!

What do you think? Do you have a different opinion or other practices?

Tags: , , , ,