JavaScript and HTML – When Should JavaScript Generate HTML?

htmljavascript

I try to generate as little HTML from JavaScript as possible. Instead, I prefer to manipulate existing markup whenever I can and only generate HTML when I need to dynamically insert an element that isn't a good candidate for using Ajax. This, I believe, makes it far easier to maintain the code and quickly make changes to it because the markup is easier to read and trace. My rule of thumb is: HTML is for document structure, CSS is for presentation, JavaScript is for behavior.

However, I've seen a lot of JS code that generates mounds of HTML, including entire forms and content-heavy modal dialogs. In general, which method is considered best practice? In what circumstances should JavaScript be used to generate HTML and when should it not?

Best Answer

Whenever I have encountered heavy HTML generation in javascript, it was almost solely in a stand-alone UI plugin. It makes sense, as it allows to encapsulate the entire plugin in a single .js file (+ a .css to customize styles), thus making it easily reusable, distribuable, and independent from the framework used in the application.

So if you're writing a stand-alone javascript plugin or a generic UI component which you would like to use across different applications, such an approach has its upsides. Otherwise, I think it's both cleaner, easier to write and easier to maintain when you keep html generation away from javascript and on the server side.