Reputation: 23
I want to add to div#container a div inside another div and then get selector of the inner div. Which one is the better way to do this?
$('#container').html("<div><div class='get'></div></div>");
var div = $('#container').find('.get');
or
var div = $('<div></div>');
$('#container').html(
$('<div></div>').html(div)
);
Upvotes: 1
Views: 77
Reputation: 33993
The latter. In the first example you are traversing a lot more (because of the find
) than in the second example, which has some performance implications.
Upvotes: 1
Reputation: 29160
Either method will work, but the first method uses the same selector twice. better practice would be
var con = $('#container').html("<div><div class='get'></div></div>");
var div = con.find('.get');
Upvotes: 0
Reputation: 29925
Either way is absolutely fine. I would probably use the second way if you're adding elements, it just seems a bit cleaner.
Upvotes: 0
Reputation: 60526
var div = $('<div />');
$('#container').html('').append(div);
I don't think you can use jQuery object as argument for html()
Upvotes: 0