Reputation: 26303
Given HTML:
<div id="div-a"></div>
<div id="div-b"></div>
<div id="div-c"></div>
And a previously-created jQuery selection:
var $divs = $("div");
How can I select a particular div in that selection by its id?
Note: the $divs
selection has not yet been appended to the DOM, so I can't just select directly (e.g. $("#div-b")
).
find()
selects descendants of a selection, so this does not work:
$divs.find("#div-b");
has()
/ :has()
selects elements that contain an element with the specified selector, so this does not work:
$divs.has("#div-b");
Upvotes: 0
Views: 72
Reputation: 707696
If you want to only examine elements within a particular jQuery object that you've already created, you can use the .filter()
method:
var $divs = $("div");
var item = $divs.filter("#div-a");
This will examine only the elements within the $divs jQuery object so see if any of them match the selector "#div-a"
and will return to you a new jQuery object that contains only the matches (either zero or one object in this case).
Upvotes: 1
Reputation: 208545
I think you are looking for filter()
:
var $subset = $divs.filter("#div-b");
Upvotes: 3
Reputation: 207527
You want to use filter()
to reduce the set/.
var elem = $divs.filter("#div-b");
Upvotes: 3