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);

Related posts:

  1. JavaScript FX
  2. jQuery Library
  3. Pie Charts with jqPlot JavaScript Charting Library
  4. Style And Class
  5. Using JavaScript Charting Library jqPlot with Bar Charts
  6. Twelve Elements of JavaScript Style


5 Responses to “Dynamically Create HTML Elements with JavaScript”

  • Maxim Kulkin Says:

    There is a Low Pro library that is built on top of Prototype library that allows even more easier syntax:

    var link = $a({ href: ‘http://juixe.com’ }, ‘Hello, ‘, $b(‘Low Pro’), ‘!’)

  • brian Says:

    Not really seaing how thats “easier syntax”, its has less readability and is less convenient

  • TechKnow Says:

    I’ll agree with Brian here, that if you want to create a large chunk of HTML I prefer how jQuery allows you to simply pass in a string with valid HTML.

    That said, there are many situation that I want to create a lot of links and I just simplified that by making a function $A(url, message) saves me some repetitive typing.

  • Napolux Says:

    Nice post. I was just searching for something like this in jQuery… But I would prefer the first solution proposed…

  • TechKnow Year In Review 2009 Says:

    […] Dynamically Create HTML Elements with JavaScript […]

Leave a Reply