Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fastest selector method in jquery and CSS - ID or not?

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')

like image 539
Hakan Avatar asked May 17 '11 18:05

Hakan


People also ask

Which is faster ID or CSS selector?

Locating elements by id is faster than css. Because : id of an elements is more specific than css of an element.

Which is faster jQuery (# id or jQuery div id?

$("#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.

Which is the fastest selector in jQuery?

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.

Which is faster ID selector or class selector?

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.


2 Answers

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.

like image 155
Anurag Avatar answered Sep 19 '22 18:09

Anurag


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.

like image 25
Nobody Avatar answered Sep 17 '22 18:09

Nobody