Dynamically Create HTML Elements with JavaScript

Twenty-five percent of AJAX is the J part, the JavaScript. When working with dynamic data coming from the back end you must create the necessary DIV containers and HTML elements and append the new new elements into the document body. In FireFox you can create a new element using the createElement method on the document object. It is good to note that creating an element this way just creates a object, and does not actual insert the element into page until you append it a parent element node.

var link = document.createElement('a');
link.setAttribute('href', 'http://juixe.com');
link.innerHTML = "Hello, Juixe!";
document.body.appendChild(link);

This is all simplified with jQuery, especially since jQuery normalized the browser quarks and differences. Here is the equivalent code but using jQuery, note that you need to load the appropriate jQuery JavaScript version for this work in your browser.

var link = $('a');
link.attr('href', 'http://juixe.com');
link.html('Hello, TechKnow!');
$('body').append(link);

All that can be streamlined and broken down to two lines.

var link = $("<a href='http://juixe.com'>Hello, jQuery!</a>");
$('body').append(link);

Using jQuery you can actually create more complex HTML elements than a simple link.

var link = $("<a href='http://juixe.com'>Hello, <b>World</b>!</a>");
$('body').append(link);