mrkmg
mrkmg

Reputation: 241

jQuery how to select children elements the proper way

If I have the following html

<div id="parent">
    <div id="item1"></div>
    <div id="item2"></div>
    <div id="item3"></div>
</div>

What would be the proper way to select children of the parent div.

I have the following:

var $parent = $('#parent'),
$item1 = $('#item1',$parent),
$item2 = $('#item2',$parent),
$item3 = $('#item3',$parent);

or if

var $parent = $('#parent'),
$item1 = $parent.find('#item1'),
$item2 = $parent.find('#item2'),
$item3 = $parent.find('#item3');

is more correct. From my tests I think they both work, but just wondering what the standard convention is for this.

The reason I do not use a more direct single selector like $('#parent #item1') is the parent could change, or could be selected from a callback function, and I want to be able to select its children without directly knowing the id of the parent, but rather using a jquery object of the parent.

Upvotes: 2

Views: 166

Answers (2)

Shyju
Shyju

Reputation: 218882

If possible, i would go for selecting the child elements with its Id because the Id will (should) be unique to an element.

I would prefer children method over find

 $('#parent').children("#item1);

children is faster than find method. Refer this answer. https://stackoverflow.com/a/648014/40521

Upvotes: 0

Ryan
Ryan

Reputation: 1395

Using jQuery's .children() function.

$("#parent").children("div");

Upvotes: 2

Related Questions