45

So I've seen three ways to add html/DOM elements to a page. I'm curious what the pros and cons are for each of them.

1 - Traditional JavaScript

I believe the straight JS way to do it is by constructing each element, setting attributes, and then appending them. Example:

var myRow = document.createElement("tr");
myRow.class = "myClass";

var firstTD = document.createElement("td");
firstTD.innerHTML = "first";
myRow.appendChild(firstTD);

var secondTD = document.createElement("td");
secondTD.innerHTML = "second";
myRow.appendChild(secondTD);

document.getElementById("myContainer").appendChild(myRow);

2 - Appending a string of html via jQuery

I've noticed that most jQuery examples I see usually just append a string of html.
Example:

$("#myContainer").append('<tr class="myClass"><td>first</td><td>second</td></tr>');

3 - jQuery's .clone()

I've also seen a lot of uses and references to .clone() in jQuery.
Example:

$("#myContainer").append($(".myClass").clone());

I'd love to hear what others have to say about this.

(Also, this seems like a good candidate for a 'community wiki', but I'm not too familiar with them. Will someone comment and let me know if it should be? Thanks)

3
  • It's innerHTML rather than innerHtml. Commented Feb 4, 2010 at 20:12
  • 9
    Only two years later :) Commented Apr 25, 2012 at 18:34
  • 11
    Better late then never, right? ...right? :) Commented May 3, 2012 at 17:58

8 Answers 8

64

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");
Sign up to request clarification or add additional context in comments.

4 Comments

@sp, how would this be chained to accomplish the <tr> example? (Not criticizing, just don't know how this works for nested elements.)
pastie.org/812613 This would create the tr, add the tds and the append it to the container
How does that code create the tr, add the tds and append it to the container? Looks like you are just adding a link to the body element!
This seems to be the official documentation.
4

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.

Comments

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

}); 

Comments

0

If you have jQuery already available, use it. If you don't want to host it, use Google's hosted version. In the end is it always calling the native javascript createElement or innerHTML methods anyway. So I'd use #2, and #3 if I specifically had to clone an existing element on the page.

Comments

0

If you're working with large amounts of HTML you want to reuse then I'd suggest you look at: http://api.jquery.com/jQuery.template/ which is final, but will be replaced by something better.

I use it in a production environment and it's great, as for smaller pieces of html what sp. said is the best way

2 Comments

That is a 404; do you mean codepb.github.io/jquery-template or something else?
This is a discontinued plugin, though originally official, there are better solutions now such as mustache.js etc...
0

Clone existing Content...

var $html = $template.clone();
 $html.find(''); ///after change content...  

Because of clone content is with 'DOM' properties. Then u can change this tags,properties,value then append it..

Comments

0

You can add or insert elements into the DOM using two jQuery append() or prepend() methods. The append() method inserts content at the end of matching elements, while the prepend() method inserts content at the beginning of matching elements.

HTML Code:

<button>Add item</button>
<ul>
  <li>lorem ipsum</li>
  <li>lorem ipsum</li>
  <li>lorem ipsum</li>
</ul>

JQuery Code:

  $(document).ready(function(){
    $("button").click(function(){
      $("ul").append("<li>lorem ipsum</li>"); 
    });
  });

You can see an example here: How to add DOM element in jQuery

Comments

-2

The cleaner way to do is using jQuery.

$('tr').addClass('myClass') like syntax. This is easy to read, understand and maintain.

1 Comment

This is not related to the post at all.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.