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?
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 usechildrenon it:Or actually, technically, you don’t need the variable:
But I find long chains like that hard to read, hard to maintain, and hard to debug.