简体   繁体   中英

Jquery find vs id attribute

Currently I am looking for the quickest way of getting access to an element.

What is quicker:

$('body').find('#elemID');

vs.

var id = $('#elemID');

Document.getElementById() is fastest of all, and doesn't require jQuery. Then, you have the option of wrapping it in jQuery using the $ , if and when you need jQuery functionality.

Quick answer is that it doesn't matter but if you have to choose one anything other than the first.

if you're worried about performance look for bottlenecks, not micro-optimizations.

Try to use vanilla js if possible but if you're using Jquery might aswell get the most from it.

 const body = () => $('body').find('#elemID'); const id = () => $('#elemID'); const idJs = () => document.getElementById('elemID'); function performanceCalc(fn, params) { const start = new Date() const result = fn() const end = new Date() console.log(`Result: ${result} ${params}. Execution Time: ${end - start} ms`) } performanceCalc(body, 'body') performanceCalc(id, 'id') performanceCalc(idJs, 'idJs') 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="elemID"></div> 

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