Jiew Meng
Jiew Meng

Reputation: 88377

Generating elements in jQuery

i wonder if below, generating content the jQuery 1.4 way

$("<div />", {
  "class": "loading",
  "html": "some html code here"
}).appendTo("#elem");

or the normal "easy" way is better. any performance or benefits from either?

$("#elem").append("some html code here");

oh i just thought of 1 benefit of the 1st, i can add event handlers. is this the only benefit?

var a = $("<a />", { href: "#", click: function() {}, text: "link text"});

on a side note, if i want to add the above link in the middle of some content i will do ...

var a = $("<a />", { href: "#", click: function() {}, text: "link text"});
var div = $("<div />", { html: "here is some content " + a.html() + " here is more html" });

right?

Upvotes: 1

Views: 54

Answers (1)

jAndy
jAndy

Reputation: 236192

You can add like anything in the 1.4.x way:

$('<div/>', {
     'class:'    'someclass',
     css:        {
          width: '200px',
          height:'200px'
     },
     click:      function(e){
          alert($(this).data('mydata'));
     },
     data:       {
          mydata: 'Yay!'
     }
});

As for performance, I didn't benchmark it yet but I can hardly believe that this is much slower than doing

$('<div></div>').click(function(){}) // etc.

Depending on the markup you want to add dynamically, it can really be faster to concatenate string literals and append one chunk of html markup once. In that scenario you would need to use .live() or .delegate() handlers to have event handlers.

Maybe I misunderstand your goal in your approach at the end. Why would you construct an element with jQuery along with an event handler to lose all that information by putting just the html string into that div?

You should use .append() or .appendTo() here instead.

var a = $("<a />", { href: "#", click: function() {}, text: "link text"});
var div = $("<div />").append(a);

Upvotes: 3

Related Questions