John
John

Reputation: 263

Jquery - Accessing nested child elements

Assume I have the following HTML -

<DIV id="ParentDiv">
    <DIV id="SubDiv1"></DIV>
    <DIV id="SubDiv2">
        <INPUT id="input">
    </DIV>
</DIV>

To access the input element using jquery, it would be simply $("#input"). What I'm trying to do is access it, assuming I only know the ID of the top level div.

Currently I have

$($($("#ParentDiv").children()[1]).children()[0])

Which does seem to work. Is there a cleaner way of writing this, or is the way I am doing it ok?

Upvotes: 26

Views: 59503

Answers (7)

manashb
manashb

Reputation: 177

try this

jQuery('#input').val();

Upvotes: 0

Murtaza
Murtaza

Reputation: 3065

if you need to find the input from SubDiv2 only upon having parentDiv information you can use

$("#ParentDiv div:eq(1) input")

or

$("#ParentDiv div:eq(1)").find("input")

Where eq(1) will get you with the second div inside ParentDiv

Upvotes: 6

Stijn Geukens
Stijn Geukens

Reputation: 15628

how about

$("#ParentDiv :input")

Upvotes: 2

dfsq
dfsq

Reputation: 193261

You can try:

1. $('#ParentDiv input')
2. $('input', '#ParentDiv')
3. $('#ParentDiv').find('input')

Upvotes: 9

dknaack
dknaack

Reputation: 60438

Many ways to do it. Here is one

$("#ParentDiv > div:eq(1) > input")

Upvotes: 2

jAndy
jAndy

Reputation: 235962

You would just perform a .find() implicitly or explicitly:

$('#ParentDiv input');  // implicitly

$('#ParentDiv').find('input'); // explicitly

Reference: .find()

Upvotes: 47

Teun Pronk
Teun Pronk

Reputation: 1399

Try this:

 $('#ParentDiv').find('input');

Upvotes: 3

Related Questions