user1796666
user1796666

Reputation:

jquery append and appendTo

I just want to know if there is any difference (especially in terms of performance) between these two approaches:

1)

$('.container').append('<div class="divChild">test div</div>'); 
$('.container .divChild').click(function() { alert('test'); });

2)

var $childDiv = $('<div class="divChild">test div</div>');
$childDiv.appendTo($('.container')).click(function() { alert('test'); });

So basically the second approach seems to be much faster since I don't really have to search for the divChild div twice, but I need to add click event to the div. Is that so?

Upvotes: 2

Views: 4164

Answers (2)

Ram
Ram

Reputation: 144659

Another option is:

$('<div/>', {
    'class': 'divChild',
    'text': 'test div',
    'click': function(){
       alert('test');
    }
}).appendTo('.container');

http://jsfiddle.net/SANMW/

Upvotes: 2

T.J. Crowder
T.J. Crowder

Reputation: 1073978

The first point to make here is: Unless you're doing this a lot (thousands of times in a very short period of time), it's unlikely to matter.

But I would suspect the most efficient thing to do would be to remember the result of $('.container') and then use children on it:

var c = $('.container');
c.append('<div class="divChild">test div</div>'); 
c.children('.divChild').click(function() { alert('test'); });

Or actually, technically, you don't need the variable:

$('.container')
    .append('<div class="divChild">test div</div>')
    .children('.divChild')
      .click(function() { alert('test'); });

But I find long chains like that hard to read, hard to maintain, and hard to debug.

Upvotes: 2

Related Questions