Reputation: 6315
I have this element in the DOM: <div id="main" class="main"></div>
. Is there any difference between selecting the element by $('#main') vs $('.main:first')?
EDIT: Forgot to mention that this is assuming that this element is the only element with classname "main".
Upvotes: 1
Views: 294
Reputation: 79830
EDIT: Forgot to mention that this is assuming that this element is the only element with classname "main".
There is NO difference since there is only one .main
and so selecting by $('#main')
or $('.main')
would return you the same result.
In performance aspect there is but you can ignore it, unless you use high-fi animations or huge DOM manipulation.
$('#main')
- Faster, neater and efficient
$('.main:first')
- class selector is slower compared to ID selector and :first
filter is slow.
-> You don't need :first
, just $('.main')
will return you the desired result.
Other options -
$('.main')
- Slower than ID selector
$('div.main')
- Slower than ID Selector still better than just $('.main')
Proof - http://jsperf.com/jquery-class-vs-id-v2
Upvotes: 3
Reputation: 10736
The ID Selector is stronger as jQuery traverses the DOM ID's should be unique (meaning only 1 per view) whereas you can have multiple main classes.
Upvotes: 0
Reputation: 6870
$("#main") will probably be a bit faster since it uses the ID.
Also, if you add another element with the .main class before the original one, then it would fail.
Upvotes: 1
Reputation: 142921
Yes. If that element is not the first element with the class main
then it will not be selected.
Upvotes: 1