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

2 Answers 2

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');

Sign up to request clarification or add additional context in comments.

Comments

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();

1 Comment

find() is correct, but I don't think filter() works like that: jsfiddle.net/o8Ldzo5z/1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.