Definition and Usage
Since the value of the id attribute must be unique in HTML, this function is useful for finding an element quickly.
Basic Example
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>getElementById() Example</title>
</head>
<body>
<p id="hello">Welcome! Nice to meet you!</p>
<script>
const changeColor = newColor => {
const element = document.getElementById("hello"); // Finds the element with id="hello".
element.style.color = newColor;
}
</script>
<button type="button" onclick="changeColor('red');">Change to Red</button>
<button type="button" onclick="changeColor('blue');">Change to Blue</button>
</body>
</html>
Welcome! Nice to meet you!
Syntax
document.getElementById(id);
Parameters
id |
The value of the id attribute of the element to find. This value is a case-sensitive string. |
|---|
Return Value
Things to Keep in Mind
There are a few things to keep in mind when using the getElementById() function.
Preventing Errors When the Target Element Does Not Exist
The getElementById() function returns null if the element to find does not exist.
In the following example, an error occurs.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Error When the Target Element Does Not Exist</title>
</head>
<body>
<button type="button" id="btn1">Button 1</button>
<button type="button" id="btn2">Button 2</button>
<button type="button" id="btn3">Button 3</button>
<script>
/* There is no element with id="btn-4". */
const btn4Element = document.getElementById("btn-4"); // Finds the element with id="btn-4".
// btn4Element becomes null instead of an element object.
// Uncaught TypeError: Cannot read properties of null (reading 'addEventListener')
btn4Element.addEventListener("click", () => {
// ...
});
</script>
</body>
</html>
To listen for the event that occurs when a button is clicked, the addEventListener() event listener function is used with objects that support events (such as element objects, the Document object, and the window object).
Since null is not an object that supports events, a TypeError occurs.
Situations like this are common.
In this example, the HTML elements and JavaScript are written inline within the HTML document so that they can be easily seen together at a glance, but this situation can occur when JavaScript is placed in a separate file. This is because it is not always easy for developers to see everything at a glance.
To help prevent errors in these situations, it is recommended to write the code as follows.
if() statement
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Error When the Target Element Does Not Exist</title>
</head>
<body>
<button type="button" id="btn1">Button 1</button>
<button type="button" id="btn2">Button 2</button>
<button type="button" id="btn3">Button 3</button>
<script>
/* There is no element with id="btn-4". */
const eleBtn4 = document.getElementById("btn-4"); // Finds the element with id="btn-4".
// eleBtn4 becomes null instead of an element object.
if (eleBtn4) {
eleBtn4.addEventListener("click", () => {
// ...
});
} else {
console.warn("No element with id='btn-4' was found.");
}
</script>
</body>
</html>
In this example, an if() statement is used to evaluate whether the eleBtn4 variable is null.
If the condition evaluates to true, the code is executed. Otherwise, a warning message is printed to the console.
The try..catch statement can also be used instead of an if() statement.
try..catch statement
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Error When the Target Element Does Not Exist</title>
</head>
<body>
<button type="button" id="btn1">Button 1</button>
<button type="button" id="btn2">Button 2</button>
<button type="button" id="btn3">Button 3</button>
<script>
/* There is no element with id="btn-4". */
const btn4 = document.getElementById("btn-4"); // Finds the element with id="btn-4".
// btn4 becomes null instead of an element object.
try {
btn4.addEventListener("click", () => {
// ...
});
} catch (error) {
console.warn("No element with id='btn-4' was found.");
}
</script>
</body>
</html>
Although a try..catch statement can also be used, checking whether the returned value is null with an if() statement is generally preferred.
The Value of the Target Element's id Attribute Is Case-Sensitive
The id parameter of the getElementById(id) function is a case-sensitive string.
<div id="user-id"></div>
id parameter is case-sensitive.
getElementById("User-id");
getElementById("User-Id");
getElementById("USER-ID");
id parameter must match the letter case exactly.
getElementById("user-id");
getElementById() Is Only a Method of the document Object
The getElementById() function is a document-only method used to find elements based on the entire HTML document.
Therefore, it cannot be used on Element objects accessed through properties such as parentNode and parentElement.
<div id="container">
<div id="child"></div>
</div>
Element objects.
const container = document.getElementById("container");
// Finds the matching element and returns an Element object.
// 'container' is an 'Element object', not the 'document object'.
// Uncaught TypeError: container.getElementById is not a function
const child = container.getElementById("child");
getElementById() function is only a method of the document object.
const child = document.getElementById("child");
Specifications
| Specification | |
|---|---|
getElementById()
|
DOM Standard #ref-for-dom-nonelementparentnode-getelementbyid② |
Browser Compatibility
| Method |
Desktop Chrome
|
Desktop Edge
|
Desktop Firefox
|
Safari
|
|---|---|---|---|---|
getElementById()
|
1 | 12 | 1 | 1 |
References
See Also
- JavaScript getElementsByTagName() Function – A Complete Guide
- JavaScript getElementsByClassName() Function – A Complete Guide
- JavaScript querySelectorAll() Function – A Complete Guide
- JavaScript querySelector() Function – A Complete Guide
- JavaScript closest() Function – Finding the Closest Ancestor Element