jQuery select child element by class with unknown path

JqueryClassHtmlSelectorCss Selectors

Jquery Problem Overview


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?

Jquery Solutions


Solution 1 - Jquery

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.

Solution 2 - Jquery

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

Solution 3 - Jquery

This should do the trick:

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

Solution 4 - Jquery

Try this

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

Hope it will help

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAdam JamesView Question on Stackoverflow
Solution 1 - JqueryCaseyView Answer on Stackoverflow
Solution 2 - JquerycfsView Answer on Stackoverflow
Solution 3 - JqueryJoe MeyerView Answer on Stackoverflow
Solution 4 - JquerySonu SindhuView Answer on Stackoverflow