manojadams
manojadams

Reputation: 2427

How to find the first direct child element of a div

This should be easy but I am not able to do it.

I have a div element with id "LeftScrollableDiv" and I am trying to find the first child element under it:

$("#LeftScrollableDiv:first-child");

<div id="LeftScrollableDiv:first">
   <table></table>
</div>

But the result is null. Any help??

Upvotes: 22

Views: 65842

Answers (4)

WonderWorker
WonderWorker

Reputation: 9092

The following didn't work for me:

$('#LeftScrollableDiv').children().first();

If you find the same, then you can treat the object returned by the children() method like an array.

To get the first element:

$('#LeftScrollableDiv').children()[0]

To get the last element:

$('#LeftScrollableDiv').children()[$('#LeftScrollableDiv').children().length-1]

Upvotes: 0

Esailija
Esailija

Reputation: 140234

The :first-child checks if its subject is the first child of its parent. In thise case you are trying to select element with id #LeftScrollableDiv that is the first child of its parent. All the : selectors just filter previous selection, they don't select any new elements.

There is unfortunately no .firstChild method in jQuery so you must always select all the children first and then take out the first one.

A possible selector to do it is:

"#LeftScrollableDiv > :first"

Which is far more efficient than > :first-child.

Upvotes: 4

user657496
user657496

Reputation:

$('#LeftScrollableDiv').children().first();

API

Upvotes: 54

jagm
jagm

Reputation: 576

$("#LeftScrollableDiv > :first-child");

Upvotes: 11

Related Questions