Tuesday, 1 November 2016

ASP.NET Tips #79 - Use fastest HTML DOM getElementById() method to access any HTML element

The document.getElementById() or jQuery(#id) method returns the element that has the ID attribute with the specified value.

This method is one of the most common methods in the HTML DOM, and is used almost every time you want to manipulate, or get info from, an element on your document.

Recently I did some research and found that there are many ways to access HTML element, but I'm concerned about the overall performance in terms of speed & browser compatibility. Hence, I created a JavaScript Benchmark Test based on 13 common methods and tested on 5 popular browsers.

Test - Environment

  • CPU: Intel i7-4770 @3.4GHz (8 cores)
  • Memory: 8GB DDR3
  • Hard Disk: Intel 535 120GB SSD (Read: 540MBps, Write: 450MBps)
  • Network Card: Gigabit
  • Internet Bandwidth: 100Mbps (Download: 100Mbps, Upload: 100Mbps)
  • Platform: Windows 10 (64-bit)

Test - HTML DOM methods (Pure JavaScript vs jQuery)

  1. getElementById()
  2. getElementsByClassName()
  3. getElementsByTagName()
  4. querySelector(#id)
  5. querySelector(.id)
  6. querySelectorAll(#id)
  7. querySelectorAll(#id)
  8. jQuery(#id)
  9. jQuery(.id)
  10. jQuery(tag#id)
  11. jQuery(tag.id)
  12. jQuery + getElementById
  13. jQuery + getElementByClassName

Test - Modern Browsers

  1. IE 11 on Windows 10
  2. Edge 14 on Windows 10
  3. Google Chrome 54 on Windows 10
  4. Mozilla Firefox 49.0.2 on Windows 10
  5. Opera 41 on Windows 10
Test - Modern Browsers (Updated on 27 Dec 2016)
  1. Google Chrome 55 on Windows 10
  2. Mozilla Firefox 50.1 on Windows 10
  3. Opera 42 on Windows 10
Test - Modern Browsers (Updated on 15 Feb 2017)
  1. Google Chrome 56 on Windows 10
  2. Mozilla Firefox 51.0.1 on Windows 10
  3. Opera 43 on Windows 10

Test Result


Test Result (Updated on 27 Dec 2016)

Test Result (Updated on 15 Feb 2017)

Conclusion

Based on the test result, Pure JavaScript document.getElementById() is proven to be the fastest HTML DOM on the planet so far.
You may perform the same test on your own environment at: https://www.measurethat.net/Benchmarks/Show/554

Browser Support

document.getElementById() is fully compatible with all browsers.

To learn more about document.getElementById(), kindly visit http://www.w3schools.com/jsref/met_document_getelementbyid.asp