javascriptjquerydom-traversal

How to select a single child element using jQuery?


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?


Solution

  • 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];
      }