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

The name is a bit confusing, but here is what I need:

  • I have a set of elements containing all the elements h3on the page.
    In jQuery terms: var mySet = $('h3').

  • I also have a div element var myContainer = $('div#foo')

  • I need to find all the elements in the set mySetthat are children of the element myContainer.

Any ideas? I am sure that there is a magic liner for this, but I can’t think of anything. I would prefer not to iterate over each element in the set manually and use .closest(myContainer)or something similar to determine the relationship.

Please note that in my scenario I cannot use a new type selector $('div#foo h3')(that would be too simple), since I do not have access to the actual values ​​of the selector. Therefore, it must be dynamic.

+3
source share
3 answers

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

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

filter works:

myContainer.children().filter(mySet)

Remember, however, that this is undocumented as far as I can see, so it can change. can also accept a set of elements that works similarly.
.not

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

+1
source

.filter, , :

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

, jQuery, . selector.

+2

I don't know about jQuery, but in YUI3 the nodelists returned from the selector request contain the actual selector string used to create the list, maybe jquery provides similar functionality?

0
source

Source: https://habr.com/ru/post/1750250/


All Articles