Categories
javascript jquery jquery-selectors

How to get the children of the $(this) selector?

2362

I have a layout similar to this:

<div id="https://stackoverflow.com/questions/306583/..."><img src="https://stackoverflow.com/questions/306583/..."></div>

and would like to use a jQuery selector to select the child img inside the div on click.

To get the div, I’ve got this selector:

$(this)

How can I get the child img using a selector?

0

    2950

    The jQuery constructor accepts a 2nd parameter called context which can be used to override the context of the selection.

    jQuery("img", this);
    

    Which is the same as using .find() like this:

    jQuery(this).find("img");
    

    If the imgs you desire are only direct descendants of the clicked element, you can also use .children():

    jQuery(this).children("img");
    

    1

    • 587

      for what it’s worth: jQuery(“img”, this) is internally converted into: jQuery(this).find(“img”) So the second is ever so slightly faster. 🙂

      Jan 8, 2010 at 23:49

    485

    You could also use

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

    which would return all imgs that are descendants of the div

    1

    • In general cases, it seems like $(this).children('img') would be better. e.g. <div><img src="..." /><div><img src="..." /></div></div> because presumably the user wants to find 1st-level imgs.

      Oct 28, 2014 at 6:47

    145

    If you need to get the first img that’s down exactly one level, you can do

    $(this).children("img:first")
    

    0