What is / are some recommended ways to write JavaScript as to control behavior of showing HTML on screen, while keeping well-maintainable code? Basically, I started to look for ways to keep HTML/CSS out of JS (assuming it's the recommended practice), but I might as well check into the latest ways of writing JavaScript well. See below for more details.

My specific problem

I have JS files that look something like this:

var selection = eval("(" + document.getElementById("result").innerHTML + ")");

if (selection[index].selected) {
    result += '<TABLE class="list_grey" style="float: left; margin-left: 20px;">';
    result += '<TR>';
    result += '<TH colspan="2">Data</TH>';
    result += '</TR>';

    var flag = "All";

    if (selection[index].flag == 'P')
        flag = "Premium";

    result += '<TR>';
    result += '<TD>Flag</TD>';
    result += '<TD>' + flag + '</TD>';
    result += '</TR>';
    result += '</TABLE>';

document.getElementById('final').innerHTML = result;

In fact, entire JS codebase I work with is plagued by this. You can see here HTML, CSS JS, and JSON (selection var gets its content from JSON prepared by PHP earlier). I want to make this better.

My experience level

I am new to writing good JS or to having experience with JS patterns, tools, tips, techniques, and so on. I am looking for help with those.

My specific issue:

I have a series of tables and data to be shown to the user. It is a "series", so user can select which "element" of the series is currently active on the screen. An "element" is essentially an HTML partial (with JS and CSS and HTML), and is described below:

"element": a block of HTML that serves as static data (tables, titles, and divs), and a long JSON string that encodes some previously prepared data. JSON string is assigned to a JS variable and that JSON data/JS variable stores records numbered 1 through n, where each i holds various data to be injected into the block of HTML, forming "HTML partial".

I have navigational buttons on the screen, allowing user to step through the "series", where the HTML is the same, but the data inside it changes.

I am looking for a good way to write this "step through HTML blocks" functionality using what is considered to be good maintainable JS code. Namely, I am looking for the following characteristics:

  • separation of concern
  • cleaner code - I need tools or techniques to allow me to avoid mixing HTML with JS with CSS (as in seen my example), unless where necessary or convenient. (what I have now is not convenient)
  • I prefer techniques rather than tools, but open to considering/evaluating well-established tools. By "techniques", I mean pure JS, HTML, CSS, PHP approaches. By "tools", I currently know and trust jQuery, and for other tools prefer to have some track record to them.

Note on HTML visibility/hiding

I should also perhaps note that in my case HTML is static, aka it does not change structurally, as I step through the elements. However, based on the JSON/selection variable, some blocks of HTML are show/hidden (as is shown in my example). Once they are shown/hidden at page render time, they stay shown/hidden throughout stepping through selection.

  • 3
    Have you considered a template engine? Something like mustache.js, for example.
    – yannis
    Jul 23, 2014 at 16:14
  • I think your concern about libraries and frameworks is a bit dated. AngularJS, EmberJS, KnockoutJS, BackboneJS, Knockback, etc. all fit your desires perfectly, and some of them have been around for years now, and have thousands of implementations. Use Google Trends if you're worried about something being a flash in the pan or something. Check out GitHub activity if you're worried about it going stale.
    – Calphool
    Jul 23, 2014 at 18:34
  • 1
    my concern on tools is mostly "learning new ways of doing same things that worked perfectly well before". In other words, is using a new tool really going to make things towards the better, or is it going to add another syntax and API to know and maintain.
    – Dennis
    Jul 23, 2014 at 18:40
  • Thanks. I'd be interested in more detail on implementing mustache, in particular ... would it be correct to say that it is a faster-to-implement solution for my case (compared to say AngularJS), but in the long run it won't help my codebase to improve as much as when using an mvm pattern?
    – Dennis
    Jul 23, 2014 at 20:48

4 Answers 4


Use a mvw (model/view/whatever) pattern

  • model: "pure" javascript library modelling abstract concepts. This part usually contains objects & methods names related to the application domain (car business -> car objects / insurance contracts) and the data access logic.
  • view: a custom language describing how your UI look like. Preferably, the language should be close to HTML.
  • something to make both part communicate without having one depend too much on the other. A change in the model data must result in a change in the corresponding elements of the view (model -> view). A mouse click mouse result in a method call somewhere in the model (view -> model).

With those concepts, you can choose different stacks

  • You can use a big framework such as angular. The views are html dom template. The model is divided between controllers & services.
  • you can use backbone (~model) + jquery (~view)
  • you can use react.js

... the list goes on. The number of tools available is actually pretty scary. Check http://todomvc.com/ for a nice list of examples.

Example solution with angular

In angular, the connection between the model & the view is performed with a viewmodel & dual way data binding. A view model is a javascript object. Both the view & the model can read & write to this object, and react to changes.

in your view, you write the HTML:

<TABLE class="list_grey" style="float: left; margin-left: 20px;" ng-hide="hideAll">
<TR ng-repeat="row in rows">
    <td ng-repeat="val in row" ng-class="{selected : val.sel}"> {{ val.label }} </td>

in your controller, you only deal with javascript values:

$scope.rows = [
    [{label : "foo"}, {label : "bar"}],
    [{label : "foo2"}, {label : "bar2", sel : true}]

$scope.hideAll = false;

ng-repeat allows you to display a list of items. ng-class & ng-hide are used to control the class & visibility of the elements.

Closing words

Using other frameworks, the resulting organization may vary, but the essential separation still exists. In react.js, the data binding is unidirectional, which implies different construct. The mvw framework usually deals with the communication between the components, so you don't have to use jquery at all.

This is a good thing if your project isn't trivial. Managing a complex app with only jquery can lead to a mess of callback interactions which may become hard to maintain.

Using a full mvw framework such as angular or ember requires some learning. Some other libraries have a smaller scope such as react.js & knockout.js.

Of course you don't have to start learning one of these tools right now. The important thing is to achieve the separation between the view & the model. You can use jquery to write functions which will edit the dom according to observation made on a pure javascript library.

You can also use jquery to write the (view -> model) callbacks. (model -> view) can be written using publisher/observer. This part should be as small as possible, and be the only thing connecting the model and the views.

  • thanks! can you add a bit more detail to things? Specifically, what do you mean by "abstract concepts", and what is "something to make both part communicate", (i.e. what are these called/how do these work with respect to Angular, for example?) - right now they sound pretty abstract. Also using a pattern looks like a longer-term strategy, rather than a drop-in "done tomorrow" solution and is a shift in paradigm compared to the current code base. Definitely something I will be looking at for the long term.
    – Dennis
    Jul 23, 2014 at 20:34
  • @dennis I hope the new version is better. I will see if I can improve it again later. Jul 23, 2014 at 21:21

Depending on which browsers you need to support, you may be able to take advantage of the HTML 5 template tag.

The template tag allows you to keep your partial HTML elements in the HTML file but not have them rendered in the browser. In order to actually display the contents, you clone the template's contents and add it to the DOM using javascript. You can clone and add as often as needed during runtime, while only defining and maintaining the contents of the HTML once, keeping things nice and DRY.

Keeping your CSS and JS in separate files is also a very good practice, so that you can perform minification to improve how fast your page downloads. It also allows your css and js to be re-used across multiple pages in your site and cached by the browser between those requests, again improving the site's performance. It also allows you to use different tools for the different file types, or use a web development IDE that has different syntax highlighting and other language-specific features based on the language of the file.

HTML 5 rocks has a good tutorial on the template tag with sample code.

Putting it Together

  • extract the HTML in your JS and place it into a template tag in your main html file

  • place css in its own file

  • place JS in its own file

  • include the css and js files in your html file

  • in your js file, create separate functions to clone the template tag's contents, add your JSON data into the appropriate part of the cloned contents, add the contents to the DOM.

  • in your js file, create a function to call the above functions appropriately based on the selection var

  • bind your navigational events to the nav buttons


Since this is a new tag, it only works in a few browsers (currently Firefox and Chrome). If your site needs to work in other browsers, you will want to use a polyfill which is alternate javascript and html code that handles the cases where the browser support is not there yet.

  • just fyi: I need to support Firefox, which is routinely updated to latest version
    – Dennis
    Jul 23, 2014 at 18:43
  • If you'd like to do this, but still need to support all browsers (unfortunately IE11 doesn't use it it seems) try putting templates inside this: <script id="myTemplateName" type="text/mymadeuptemplatetype">. Since it doesn't know what that type is, it won't parse it as a script, and you can still retrieve the contents.
    – Katana314
    Jul 23, 2014 at 18:50

My initial thoughts

  • extract HTML from JS, and place HTML in HTML file (same with CSS)
  • load JS in parent container's HTML file
  • in JS file use JS/jQuery to show/hide DIVs in HTML as needed as per selection var
  • use JS/jQuery to bind navigational events to buttons
  • have navigational events populate table cells via assigned id attributes.

A bit of a pain to rewrite what I have now, but hopefully the end result will be more maintainable and easier to extend / customize. i.e. for HTML I can go to HTML and edit that and use HTML tools for things there, rather than dealing with HTML embedded as strings in JavaScript. Same with CSS. I am still not sure if that effort will be entirely worth it, as things do work as they are now... except that it's a long mess of a JS file.


Loading data

var selection = eval("(" + document.getElementById("result").innerHTML + ")");

That is a pretty horrible method. First of all, any legal HTML tags in the JSON code would be parsed as so, this could be used for an injection attack. Second, depending on browser, a lot details may be different in the innerHTML string from the original text. In general, setting innerHTML should be done with caution, and only if it provides substantial advantages to the alternatives. And I simply can't think of any legitimate reasons for reading from innerHTML.

I would consider a separate JSON file loaded with XMLHttpRequest to be the prime method for delivering data to a JavaScript browser application. On the back-end you can generate the JSON file with PHP if you like.

If you really want the data directly in the HTML file a much better place to put it would be inside a script tag, PHP can do that just fine:

    var dataFromServer = <?php echo str_replace('</','<\\/',$wellFormedJSON)?>

Note that since the sequence </script> may be part of well-formed JSON, but not part of JavaScript in an HTML file it is necessary to escape the </ sequence, this is usually done as <\/ which is equivalent as part of a JSON or JavaScript string.

Alternately you can make a JSONP file and load it with a normal script tag, but note that this makes the data available to other domains, thus you cannot put private data in such a file.

Dynamic page

Hiding and showing elements using CSS is a reasonable method of making dynamic content, but it doesn't work for everything, and it places the HTML far from the code that modifies it, which can be a bit of a pain.

innerHTML seems easy to use, unfortunately it is a method quite prone to introducing security issues, as what you thought was simple text may be interpreted as HTML tags. It is perfectly possible to use innerHTML in a safe manner by escaping everything dangerous, but you only need to make one mistake to introduce a hole. It is usually the best performing method of generating new DOM, but save for the few cases where this actually matters I'd advice that you stay clear of it, especially as an inexperienced developer.

You can create DOM elements using document.createElement and related methods. It is relatively straightforward and doesn't have any security traps. It also allows attaching functions in a local scope as event handlers, which is quite nifty once you start using closures. But the resulting code tend to be quite long and a somewhat tedious to write, which I would consider the primary reason to get a library for DOM building.

  • Thanks. Can you direct me to info on how to pass JSON as a file? It seems a bit tricky when pages are loading in real time, to save a file to a file system on a possibly mechanical drive, using PHP, but then read it back right away in HTML that is rendered mere milliseconds later. So maybe I misunderstood the approach.
    – Dennis
    Jul 30, 2014 at 14:09
  • @Dennis I mean you produce the JSON as output of a PHP script, so that it is sent as an HTTP response, you wouldn't need to save the result the disk to do that. Jul 30, 2014 at 21:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.