When dynamically creating an HTML element in jQuery, is there any difference performance-wise between the following two methods?
// First approach
var elem = $('<div/>').attr('id', 'foo').addClass('myClass');
// Second approach
var elem = $('<div id="foo" class="myClass" />');
Also, are there any obvious advantages of one approach over the other, or is it just a matter of taste?
I don't think many people realize that the most popular and heavily used component of jQuery - selectors - actually has a lot of magic going on behind the scenes and therefore, uses a bit of resources.
Your first approach makes more use of selectors than your second one. I think your second approach is also a lot easier to read and is cleaner. I'd stick with that one.
Approach #1 is more for if you have to modify an element that is already created, but i wouldn't actually create it that way.
Hope this helps.