The getElementById() method returns the elements that have given an ID which is passed to the function. This function is a widely used HTML DOM method in web designing to change the value of any particular element or get a particular element. If the passed ID to the function does not exist then it returns null.
Note: Each ID needs to be unique. If there are multiple elements with the same ID, only the first one will be returned.
Syntax
document.getElementById( element_ID )Parameter: This function accepts single parameter element_ID which is used to hold the ID of the element.
Return Value: It returns the object of the given ID. If no element exists with the given ID then it returns null.
Example 1: This example describes the getElementById()method where element_id is used to change the color of the text on clicking the button.
<!--Driver Code Starts-->
<!DOCTYPE html>
<html>
<head>
<title>
DOM getElementById() Method
</title>
<!--Driver Code Ends-->
<script>
// Function to change the color of element
function geeks() {
let demo = document.getElementById("geeks");
demo.style.color = "green";
}
</script>
<!--Driver Code Starts-->
</head>
<body style="text-align:center">
<h1 id="geeks">GeeksforGeeks</h1>
<h2>DOM getElementById() Method</h2>
<!-- Click on the button to change color -->
<input type="button" onclick="geeks()"
value="Click here to change color" />
</body>
</html>
<!--Driver Code Ends-->
Example 2: This example describes the getElementById() method where the element_id is used to change the content on clicking the button.
<!--Driver Code Starts-->
<!DOCTYPE html>
<html>
<head>
<title>
DOM getElementById() Method
</title>
<!--Driver Code Ends-->
<script>
// Function to change content of element
function geeks() {
let demo = document.getElementById("geeks");
demo.innerHTML = "Welcome to GeeksforGeeks!";
}
</script>
<!--Driver Code Starts-->
</head>
<body style="text-align:center">
<h1>GeeksforGeeks</h1>
<h2>DOM getElementById() Method</h2>
<h3 id="geeks">Hello Geeks!</h3>
<!-- Click here to change content -->
<input type="button"
onclick="geeks()"
value="Click here to change content" />
</body>
</html>
<!--Driver Code Ends-->
- Only available on the document object : Unlike querySelector(), you cannot call getElementById() on individual elements; it always searches the entire document because IDs must be unique.
- Extremely fast lookup : Browsers maintain an internal ID map, so getElementById() is generally the most performant way to retrieve a single element compared to CSS selector-based methods.