简体   繁体   中英

Is there an efficiency difference between finding by id and finding by class with JavaScript/jquery?

Is there an efficiency difference between finding by id and finding by class with JavaScript/jquery?

Is one better than the other? If so is it because indexes of ID or Class are made in the DOM somewhere?

Does it end up not mattering much?

Finding by ID is always faster, no matter where ( getElementById() , $('#id') , or even in regular CSS).

Since ID's are unique per page, they're much faster to find.

In addition, when using $('#id') , jQuery will map that back to the built-in getElementById() , which is the fastest way to query the DOM.

Well, logically speaking, an ID would be more efficient, as there is (should be) only one of it, so once it finds it, it will stop searching. However I am not familiar with the jQuery source, I don't know how it actually works, that's from a logic perspective.

For most browsers, the difference in speed between searching by id and searching by class name depends on how many elements have a given class. At best, there will be only one such element, and the search speed ought to be the same. At worst, there are a bazillion elements with a given class. Typically, though, you shouldn't have to worry about the speed of searching through 10-20 elements containing the same class.

A critical caveat, though: MSIE <= 8 has no native getElementsByClassName , so jQuery has to fall back to a full DOM tree search unless, eg, the element name of the wanted element is also provided. Even then. $('div.myclass') may not be much help if your document is large and exceedingly div -happy. Benchmarking is really the only way to find out.

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