Is there a best practice for generating html with javascript

Options #1 and #2 are going to be your most immediate straight forward options, however, for both options, you’re going to feel the performance and maintenance impact by either building strings or creating DOM objects.

Templating isn’t all that immature, and you’re seeing it popup in most of the major Javascript frameworks.

Here’s an example in JQuery Template Plugin that will save you the performance hit, and is really, really straightforward:

var t = $.template('<div><img src="https://stackoverflow.com/questions/220603/${url}" />${name}</div>');

$(selector).append( t , {
     url: jsonObj.url,
     name: jsonObj.name
});

I say go the cool route (and better performing, more maintainable), and use templating.

Leave a Comment