Friday, May 25, 2012

$(this) selector and children?


I'd like to use a selector to select the child img of the div I'm clicking on this example:




<div id="..."><img src="..."></div>



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




$(this)



How do I get the img with a selector?


Source: Tips4all

6 comments:

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

    jQuery("img", this);


    Which is the same as

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


    If the imgs are direct descendants of the clicked element, you can also use:

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

    ReplyDelete
  2. You could also use

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


    which would return all imgs that are descendants of the div

    ReplyDelete
  3. If you need to get the first img that's down exactly one level, you can do

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

    ReplyDelete
  4. If your DIV tag is immediately followed by the IMG tag, you can also use:

    $(this).next();

    ReplyDelete
  5. Without knowing the ID of the DIV I think you could select the IMG like this:

    $("#"+$(this).attr("id")+" img:first")

    ReplyDelete
  6. Try this code:

    $(this).children()[0]

    ReplyDelete