77

I am trying to figure out the syntax for selecting a nth-child of an element by its class, however I don't know the exact path to the element. I can't do $('parent > child > grandchild > hereIam');

So basically I need to be able to say

$('#thisElement').AllRelativesWithClass('.classToSelect')

How exactly do I do that?

0

4 Answers 4

98

According to this documentation, the find method will search down through the tree of elements until it finds the element in the selector parameters. So $(parentSelector).find(childSelector) is the fastest and most efficient way to do this.

48

$('#thisElement').find('.classToSelect') will find any descendents of #thisElement with class classToSelect.

1
  • 2
    I prefer this answer because it shows dummy selectors with syntax, unlike the accepted one.
    – jarmanso7
    Commented May 28, 2020 at 15:22
25

This should do the trick:

$('#thisElement').find('.classToSelect')
12

Try this

$('#thisElement .classToSelect').each(function(i){
         // do stuff
});

Hope it will help

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.