gr56
gr56

Reputation: 23

The best way of selecting div

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

Answers (4)

Igor
Igor

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

Dutchie432
Dutchie432

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

Thomas Clayson
Thomas Clayson

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

Andreas Wong
Andreas Wong

Reputation: 60526

var div = $('<div />');
$('#container').html('').append(div);

I don't think you can use jQuery object as argument for html()

Upvotes: 0

Related Questions