views:

183

answers:

5

Hello,

I'm learning JQuery and have found the factory function $() with its selectors quite useful. However, I cannot figure out how to select within a particular element I have named as a variable. For example:

var thisDiv = $("#myDiv");

// thisDiv looks like this:
<div id="myDiv">
<input id="apples" />
<input id="bananas" />
</div>

How would I select the input with id="apples" given only the variable thisDiv in JQuery? Thanks!

+1  A: 

You could try this

thisDiv.find('#apples');
alex
+3  A: 
$("#thisDiv #apples")

But you can also do:

thisDiv.find("#apples"); // use find method

and also:

$("#apples", thisDiv); // provide context
altCognito
Thanks for both solutions!
Jasie
+1  A: 

You should be able to select it by searching within your div like:

 $("#myDiv").find("#apples")
Pete
+1  A: 
$('#apples', thisDiv);
Luis Melgratti
+1  A: 

Perhaps yours was only an example and not representative of the proper code, but it's worth mentioning that an ID is unique per document, therefore you don't particularly need the context.

$('#apples');
$('#apples', thisDiv);  // same result, more lookups

If it was just an example, and you wanted to know how to find any element, using any selector, then yep, the other answers here are all correct.

thisDiv.find('li.myClass'); // or,
$('li.myClass', thisDiv);
nickf
Some people like to be specific with selectors in an effort to speed up finding elements, however, with using just an Id, jQuery uses (IIRC) getElementById() which is the quickest.
alex