jquery, selector for class within id
Below, how should I select the elements that contain the class my_class
within the element with id = "my_id"
?
Note that the element may also have another class, which I am not selecting for.
<div id = "my_id">
<span class = "my_class hidden">hi</span>
<span class = "my_class">hello</span>
</div>
was trying
$("#my_id [class*=my_class ]")
You can use the class selector along with descendant selector
$("#my_id .my_class")
Just use the plain ol' class selector.
$('#my_id .my_class')
It doesn't matter if the element also has other classes. It has the .my_class class, and it's somewhere inside #my_id, so it will match that selector.
Regarding performance
According to the jQuery selector performance documentation, it's faster to use the two selectors separately, like this:
$('#my_id').find('.my_class')
Here's the relevant part of the documentation:
ID-Based Selectors
// Fast: $( "#container div.robotarm" ); // Super-fast: $( "#container" ).find( "div.robotarm" );
The
.find()
approach is faster because the first selection is handled without going through the Sizzle selector engine – ID-only selections are handled usingdocument.getElementById()
, which is extremely fast because it is native to the browser.
Selecting by ID or by class alone (among other things) invokes browser-supplied functions like document.getElementById()
which are quite rapid, whereas using a descendent selector invokes the Sizzle engine as mentioned which, although fast, is slower than the suggested alternative.