JavaScript LogoWhen you need to iterate over a data set, and build markup using its elements, there are a few techniques that make this a snap

Sometimes you may need to build markup and insert it into the page, but perhaps you do not know what that markup will be. Actually, you would probably know most of what will happen: you have some markup that needs to be repeated one or more times, and in each iteration, the text in certain elements will change. A typical scenario is one in which you have multiple records in a data set, and you need to create a series of elements that will be similar, but each row in the data set will have it’s own copy of the markup and display its values. Same markup, but unique values with each iteration.

Example # 1


In Example # 1, we first created our data set (the variable “arr”), which is a JavaScript array. Each element of the array is an object literal, containing three fields. We then proceed to loop through all the elements of the array and for each one, we create a form. In each form, we mix the markup (which is the same with each iteration), but mix in the values from the data set so that when finished, each element in our data set has its own HTML form (think of it as rows in a table or records in a database). When we are finished creating the markup, we simply use the jQuery .html() method to insert our markup into the DOM, using the ID of a specific HTML element.

Two Quick Notes:

Variable Declarations – When declaring multiple variables, keep in mind that you can do so with one “var” statement, and separate each variable name with a comma. This makes things a bit easier to read and some argue that it is faster.

String Concatenation – Instead of one insanely long string, you can use the “+” operator, and break your assignments into multiple lines. Although this is JavaScript, it makes it look a bit more like actual markup.


There are, of course, much more elegant ways to do this; John Resig’s JavaScript Micro-Templating technique is a cool example. And there are plenty of others out there.  Here, I’ve simply covered the basic concept of working with data, and creating HTML on the fly to present that data in the page, regardless of the amount of data, or values it contains.

Helpful links for building dynamic HTML markup with JavaScript