teggy
teggy

Reputation: 6315

jQuery selector difference

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

Answers (4)

Selvakumar Arumugam
Selvakumar Arumugam

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

Christopher Marshall
Christopher Marshall

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

Adam Albrecht
Adam Albrecht

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

Peter Olson
Peter Olson

Reputation: 142921

Yes. If that element is not the first element with the class main then it will not be selected.

Upvotes: 1

Related Questions