What is fastest in jquery/javascript?
$('#myID .myClass')
or
$('.myClass')
What is best to use in CSS?
#myID .myClass{}
or
.myClass{}
I see now that I should have explained better. Sorry!
Ofceauce ID is a faster selector in both CSS and JavaScript. But some times you need to use class since there are multiple selectors.
Say forexample that I have i BIG html document. In the middle of the page I have:
<div id="myID">
<a class="myClass">link1</a>
<a class="myClass">link1</a>
<a class="myClass">link1</a>
</div>
If I want to target all "myClass". Would it then be better to target the ID before targeting the classes? (then I wouldn't have to do domtravel of the entire HTML document) Eg.:
Would this:
$('#myID').find('.myClass')
Be faster than:
$('.myClass')
Locating elements by id is faster than css. Because : id of an elements is more specific than css of an element.
$("#myId) The document. getElementbyId( "myId") is faster because its direct call to JavaScript engine. jQuery is a wrapper that normalizes DOM manipulation in a way that works consistently in every major browser.
ID Selector: The jQuery #id selector selects the element on the basis of the ID attribute of the HTML tag. This selector is basically used when we have to work on a single element because an ID should be unique within a web page.
The performance hit will occur when you are iterating DOM to get elements. At that time ID selector will be faster than class selector. Save this answer.
My testing on modern browsers suggests that you should go with either,
$('#id').find('.class') // or
$('.class')
but not,
$('#id .class')
Reason being that all modern browsers implement getElementsByClassName
resulting in almost-constant time lookups by class name (assuming a hash implementation). Which browsers are modern is another subjective question.
They're roughly the same in most modern browsers since class-names are hashed internally. The difference is that older browsers don't have a .getElementsByClassName
or equivalent method, so .myClass
is parsed internally to jQuery and EVERY element in the dom is walked and checked for the classname (or it uses XPath when possible).
Always try to use #myID .myClass
when possible as it allows jQuery to jump directly to #myID
and traverse from there when necessary.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With