Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I have a layout similar to this:

<div id="..."><img src="..."></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?

like image 253
Alex Avatar asked Nov 20 '08 19:11

Alex


People also ask

How do you get the children of the $( this selector in jQuery?

jQuery children() MethodThe children() method returns all direct children of the selected element. The DOM tree: This method only traverse a single level down the DOM tree. To traverse down multiple levels (to return grandchildren or other descendants), use the find() method.

How do I get all Div children?

If You want to get list only children elements with id or class, avoiding elements without id/class, You can use document. getElementById('container'). querySelectorAll('[id],[class]'); ... querySelectorAll('[id],[class]') will "grab" only elements with id and/or class.


1 Answers

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"); 
like image 77
Simon Avatar answered Oct 14 '22 01:10

Simon