Vicky Siddharth
Vicky Siddharth

Reputation: 127

how to select children id from parent id in jQuery?

Here I have parent div (div1) , by having this id I want to select the children id (children2) .

note :- i dont want to specify as children2 in code .. it should dynamic

Html :-

<div id='div1'>

<div id='children1'>
<input></input>
<input></input>
</div>

<div id='children2'>
<input></input>
<input></input>
</div>

</div>

Upvotes: 3

Views: 13658

Answers (4)

Bhushan Kawadkar
Bhushan Kawadkar

Reputation: 28513

You can iterate all children using below code

$('#div1').children('div').each(function(){
  alert($(this).attr('id'));
});

More Information on .children()

And for getting second child id you can use nth-child() like below

  var id =  $('#div1 div:nth-child(2)').attr('id');

More Information on :nth-child()

Upvotes: 0

Shawn Jacobson
Shawn Jacobson

Reputation: 1352

$('#div1').children() 

will get all child objects in an array.

$('#div1 > #children2')

will get a specific child object.

Upvotes: 1

Mohamed-Yousef
Mohamed-Yousef

Reputation: 24001

you can use

$('#div1 #children2')

or

$('#div1').find('#children2')

Upvotes: 1

Milind Anantwar
Milind Anantwar

Reputation: 82241

If the IDs are static you can simply use id selector to target the element:

$('#children2')

If Ids are not unique then you can find immediate div elements in #div1 along with :eq(1) to target second element in matched dom:

$('#div1 > div:eq(1)').attr('id')

Upvotes: 5

Related Questions