Javascript GetElementById
- DOM
- HTML
- JAVASCRIPT
- CODING TIPS
Published on 2018-08-10
The javascript Document method getElementById(String) is a fast way of returning an HTML Element Object representing the element that matches the specified id string parameter.
Quick Usage
var element = getElementById("html-tag-id-attribute");
Copy code to the clipboard Method Details
Syntax
var element = getElementById(id);
Copy code to the clipboardParamenter
The id parameter is a string with the html element id attribute to be searched.
Return Value
HTML Element Object or NULL.
Support
All browsers.
More References
Performance Comparison
Consider the following HTML setup. The goal of this test is to select the section's first div element
n t n t n t n
DOM getElementById( ) – 386.44 – FASTEST
var element = document.getElementById("id-selector-0");
DOM getElementsByClassName( ) – 141.60
var element = document.getElementsByClassName("class-selector-0")[0];
DOM querySelector( ) by id – 140.65
var element = document.querySelector('#id-selector-0');
DOM getElementsByTagName( ) – 139.91
var element = document.getElementsByTagName("div")[0];
jQuery( ) id selector – 24.52
var element = $("#id-selector-0").get(0);
jQuery( ) class selector – 8.94
var element = $("#id-selector-0").get(0);
DOM querySelector( ) by class name – 2.77
var element = document.querySelector('.class-selector-0');
DOM querySelectorAll( ) by tag name – 2.10
var element = document.querySelectorAll('div')[0];
DOM querySelectorAll( ) by class name – 1.93
var element = document.querySelectorAll('.general')[0];
DOM querySelector( ) by tag name – 1.46
var element = document.querySelector('div:nth-child(0)');
DOM querySelector( ) by composed tag – 1.40
var element = document.querySelector('section > div:nth-child(0)');
Tested in Chrome 68.0.3440, Mac OS X 10.13.6. Check this comparison on JSPERF
Have you enjoyed the read? Please show your support by sharing it with the world 🙌🏻 Share Share Share