views:

864

answers:

3

Using jQuery how do I select a single child element? I've looked at the Tranversing 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?

A: 

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.

Greg
Note that using find as in the first answer will give you all descendant elements, whereas child will give you only direct children.
Greg
+1  A: 

$('img', this)[0]

Anatoliy
+2  A: 

No. Every jQuery function returns a jQuery object, and that is how it works. This is a crucial part of jQuery's magic.

If you want to access the underlying element, you have three options...

  1. Do not use jQuery
  2. Use [0] to reference it
  3. Extend jQuery to do what you want...
$.fn.child = function(s) {
  return $(this).children(s)[0];
}
Josh Stodola
Ah ha! That was it. I was expecting the img element (trying to reference its 'src' property) instead of the jQuery object. Now I'll just use 'attr()' to get at the 'src' property.
Jonathon Watney
Thanks for 3) as well. I might consider doing that. :)
Jonathon Watney
There ya go! I had the same problem when I started with jQuery.
Josh Stodola