Asked  6 Months ago    Answers:  5   Viewed   30 times

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?

 Answers

75

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");
Tuesday, June 1, 2021
 
Optimus
answered 6 Months ago
98

If you want to apply a selector to the context provided by an existing jQuery set, try the find() function:

element.find(">:first-child").toggleClass("redClass");

Jørn Schou-Rode noted that you probably only want to find the first direct descendant of the context element, hence the child selector (>). He also points out that you could just as well use the children() function, which is very similar to find() but only searches one level deep in the hierarchy (which is all you need...):

element.children(":first").toggleClass("redClass");
Thursday, July 8, 2021
 
njai
answered 5 Months ago
96

A simple way of getting the first child element of a certain type (e.g. TextBlock) is this:

var textBlock = panel.Children.OfType<TextBlock>().FirstOrDefault();

You either get the first TextBlock or null if there isn't any.

Thursday, July 29, 2021
 
octern
answered 4 Months ago
33

Just concatenate the two:

$(selectedTable).find("td.ms-cal-nav-buttonsltr");

the selectors you tried were looking for a .ms-cal-nav-buttonsltr element underneath the td.

Sunday, August 15, 2021
 
Peter
answered 4 Months ago
41

You can use:

ui.draggable.find('a').attr('href')

This will look for the a element among all descendants of the draggable element.

To look only at the direct children of the draggable, use this instead:

ui.draggable.children('a').attr('href')
Thursday, September 2, 2021
 
Rudie
answered 3 Months ago
Only authorized users can answer the question. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :  
Share