0

This question is somewhat related to my inquiry, but doesn't quite cover what I need to understand:

jQuery caching selectors

I have this HTML:

<div id="myDiv">
    <img src="http://placekitten.com/g/200/200" />
</div>

I cached the DIV selector: var md = $('#myDiv');

How can I access the <img> sub element using the cached DIV selector?

For eg, something like:

md.('img').fadeOut();

or

$(md + ' img').fadeOut();

jsFiddle

Community
  • 1
  • 1
crashwap
  • 2,846
  • 3
  • 28
  • 62

2 Answers2

2

You want to select your md jQuery object, then use either the find() or children() method to search its hierarchy for the elements "below" it:

var md = $('#myDiv');
//the next two lines do the same thing
md.find('img').fadeOut();
md.children('img').fadeOut();

Which is better for you? Well...this expounds on the differences between find() and children(), and the answers to this question give you some helpful performance metrics to help decide.

See a working example of find() and children() at http://jsfiddle.net/o8Ldzo5z/4/

Please note, convention is to assign jQuery objects to variables prefixed with a "$": var $md = $('#myDiv');

Community
  • 1
  • 1
Jeromy French
  • 11,812
  • 19
  • 76
  • 129
1

You can use

  • find // generic method for finding descendants
  • children // for immediate children

The above as well as, filter can also be used.

md.find('img').fadeOut();
Amit Joki
  • 58,320
  • 7
  • 77
  • 95