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”.
There is NO difference since there is only one
.mainand 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:firstfilter 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