Tatu Ulmanen
Tatu Ulmanen

Reputation: 124878

How to select elements from a set that are children of another element

The title is a bit confusing but here's what I'm after:

Any ideas? I bet there's some magical one liner for this but I cannot think of any. I'd rather not loop through every element in the set manually and use .closest(myContainer) or something like that to determine the relationship.

Note that in my scenario, I cannot use a new selector like $('div#foo h3') (that would be too easy) as I don't have access to the actual selector values. So it has to be dynamic.

Upvotes: 3

Views: 105

Answers (3)

Kobi
Kobi

Reputation: 138137

Interesting. Assuming you have two jQuery collections and you don't know the selectors:

var myContainer = $('div');
var mySet = $('h3:even');

filter seems to work:

myContainer.children().filter(mySet)

Keep in mind, however, that this is undocumented as far as I can see, so it may change.
.not can also accept a collection of elements, which works similarly.

Working example: http://jsbin.com/owuru

Upvotes: 1

Andy E
Andy E

Reputation: 344763

You can use the .filter method to reduce the elements to those that match a specific selector:

mySet.filter("div#foo > *");

You can also get the selector used in a jQuery object by accessing the .selector property.

Upvotes: 2

unomi
unomi

Reputation: 2672

I don't know about jQuery but in YUI3 nodelists returned from a selector query contain the actual selector string used to create the list, perhaps jquery exposes similar functionality?

Upvotes: 0

Related Questions