How to select a single child element using jQuery?

Jonathon Watney picture Jonathon Watney · Sep 24, 2009 · Viewed 171.2k times · Source

Using jQuery how do I select a single child element? I've looked at the Traversing API and know I can select all the immediate children img elements like this:

$(this).children('img');

And to select the first child img element I could use a subscript like this:

$(this).children('img')[0];

But I guess I'm kind of surprised I can't do this:

$(this).child('img'); // no subscript, returns single element

Or have I missed something?

Answer

Greg picture Greg · Sep 24, 2009

I think what you want to do is this:

$(this).children('img').eq(0);

this will give you a jquery object containing the first img element, whereas

$(this).children('img')[0];

will give you the img element itself.