ericsoco
ericsoco

Reputation: 26303

How to select element by id within existing selection?

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

Answers (3)

jfriend00
jfriend00

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

Andrew Clark
Andrew Clark

Reputation: 208545

I think you are looking for filter():

var $subset = $divs.filter("#div-b");

Upvotes: 3

epascarello
epascarello

Reputation: 207527

You want to use filter() to reduce the set/.

var elem = $divs.filter("#div-b");

Upvotes: 3

Related Questions