Which is the optimal choice in jQuery/javascript for speed?
$('#myID .myClass')
or
$('.myClass')
What is the preferred option to utilize in CSS?
#myID .myClass{}
or
.myClass{}
In hindsight, I realize my explanation was insufficient. My apologies!
Undoubtedly, utilizing an ID is faster as a selector in both CSS and JavaScript. However, there are occasions where using classes becomes necessary due to multiple selectors.
Consider this scenario: within a large HTML document lies the following markup:
<div id="myID">
<a class="myClass">link1</a>
<a class="myClass">link1</a>
<a class="myClass">link1</a>
</div>
If the goal is to target all instances of "myClass", would it be more efficient to first target the ID before addressing the classes? (thus avoiding traversing the entire HTML structure) For instance:
Would the following perform better:
$('#myID').find('.myClass')
Than simply doing:
$('.myClass')