JQuery: How do I find an input named "apples" inside $ (this)?

I am learning JQuery and found the factory $ () function with its selectors quite useful. However, I cannot figure out how to select inside a specific element that I have named a variable. For instance:

var thisDiv = $("#myDiv");

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

      

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

+1


a source to share


5 answers


$("#thisDiv #apples")

      

But you can also do:

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

      



and:

$("#apples", thisDiv); // provide context

      

+3


a source


You can try this



thisDiv.find('#apples');

      

+1


a source


You can select it by searching your div like:

 $("#myDiv").find("#apples")

      

+1


a source


$('#apples', thisDiv);

      

+1


a source


Perhaps yours was just an example and not a representative of the proper code, but it's worth mentioning that the ID is unique for each document, so you don't really need context.

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

      

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

thisDiv.find('li.myClass'); // or,
$('li.myClass', thisDiv);

      

+1


a source







All Articles