Best way to add DOM elements with jQuery

Solution 1:

If you are using jQuery 1.4 the best way is the following:

$("<a/>", {
    id: 'example-link',
    href: 'http://www.example.com/',
    text: 'Example Page'
}).appendTo("body");

Solution 2:

If you already have a template element that you want to copy then by all means use clone().

But if you want to create an element from scratch then there's basically two methods which I think you alluded to:

  1. Create DOM elements as objects (using createElement for example).
  2. Create DOM elements as HTML (using innerHTML or jQuery's html() for example).

First if either of the methods is more intuitive or easier to write for you, I'd recommend just doing that.

Otherwise benefits of using the latter is that it is cleaner if the element has many children. For example, try to make a table row with 6 columns, each with a different class using the first method. Your code will be much longer than if you used the second method.

As far as performance goes this is a good guide http://andrew.hedges.name/experiments/innerhtml/ but the short answer is for most cases the differences are quite negligible. A good guide for performance in general as well is: http://www.artzstudio.com/2009/04/jquery-performance-rules/. The 6th tip has to do with DOM manipulation.

Solution 3:

You can try this:

 $("<div/>", {

  // PROPERTIES HERE

  text: "Click me",

  id: "example",

  "class": "myDiv",      // ('class' is still better in quotes)

  css: {           
     color: "red",
     fontSize: "3em",
     cursor: "pointer"
  },

  on: {
    mouseenter: function() {
      console.log("PLEASE... "+ $(this).text());
    },
    click: function() {
      console.log("Hy! My ID is: "+ this.id);
    }
  },

  append: "<i>!!</i>",

  appendTo: "body"      // Finally, append to any selector

});