JavaScript’s Document.getElementById()
method returns the element whose id
attribute matches the specified string or null
if no id
attribute matches the string.
Syntax
Document.getElementById(parameter);
Parameters
A string containing the value of the id
attribute of the desired element.
Return value
An Element
object or null
if no id
attribute matches the string.
Examples
Here is an example using the JavaScript getElementBId()
method.
Suppose we have the following HTML elements:
<div id="welcomeText">
<p>Welcome to the <a href="https://javascriptguide.com">JavaScript Guide</a>!</p>
</div>
How can we hide the div
element?
We can select the element with the getElementById()
method and set its display
property to none
:
let div = document.getElementById('welomeText');
div.style.display = 'none';
Additional notes
Please note that the name of the getElementById()
method ends with “Id,” not with “ID.”
Browser compatibility
Chrome
|
Edge
|
Firefox
|
Internet Explorer
|
Opera
|
Safari
|
Chrome (Android)
|
Firefox (Android)
|
Opera (Android)
|
Safari (iOS)
|
Samsung Internet
|
WebView (Android)
|
|
---|---|---|---|---|---|---|---|---|---|---|---|---|
getElementById() |
1 | 12 | 1 | 5.5 | 7 | 1 | 18 | 4 | 10.1 | 1 | 1.0 | 4.4 |