简体   繁体   中英

jQuery selector performance

为什么id选择器比jQuery中的类选择器更快?

The fastest selector in jQuery is the ID selector ($('#someid')). This is because it maps directly to a native JavaScript method, getElementById().

These points about Id Selector may also help You.

Point 1 :

Don't Qualify your selector when searching by Id .

  • searching by Id uses the browsers native getElementById method (which is very fast )

BAD Way

$("div#your-id")

BEST Way

$("#your-id")

Point 2 :

You should Always Cache your Selections to some variable

BAD Way

$("#myList").click( function() {
   $("#myList").hide(); 
});

BEST Way

var myList  = $("#myList");

myList.click( function() {
   myList.hide();  // No need to re-select #myList since we cached it
});

Browsers are able to retrieve elements by Id faster than using a class. Given an Id, one or zero elements are returned when using getElementById . This makes it possible for browsers to keep track of the Ids of the elements in a page, providing fast search operations by Id.

Searching by class name makes it necessary to look for all the elements with that given class name. Even though some browsers support getElementsByClassName , internally they need to traverse the whole DOM tree to fetch them.

jQuery selector acts as a wrapper around these native functions, together with other such as getElementsByTagName , querySelector or querySelectorAll (and it also comes with a selector library called Sizzle , that is used if the browser lacks the necessary native function).

Behavior is not defined if more than one element has this ID.

because ther references to the DOM elements with a certain ID. In addition, there shouldn

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM