.getElementById()
Published Mar 16, 2025
Contribute to Docs
The .getElementById()
method is a commonly used function in the Document Object Model (DOM) that allows developers to retrieve an HTML element by its id
attribute. This method is part of the document
object and returns the first element that matches the specified id
. If no element is found, it returns null
.
Key Characteristics
- Fast and efficient: Since IDs are unique, this method quickly retrieves elements without searching the entire DOM.
- Returns a single element: It always returns one element (or
null
if not found). - Case-sensitive: The provided
id
must match exactly, including letter casing.
Note: If multiple elements share the same
id
(which is invalid HTML),getElementById()
still returns only the first match.
Syntax
document.getElementById("elementId");
elementId
(string): Theid
of the element to retrieve.
Example
The following example demonstrates the usage of the .getElementById()
method:
<!DOCTYPE html><html lang="en"><head><title>getElementById Example</title></head><body><p id="demo">Hello, World!</p><button onclick="changeText()">Click Me</button><script>function changeText() {let element = document.getElementById('demo');element.innerHTML = 'Text changed!';}</script></body></html>
In this example, the getElementById("demo")
function retrieves the <p>
element with id="demo"
and the innerHTML
property is updated when the button is clicked.
The output will look like:
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn JavaScript on Codecademy
- Career path
Front-End Engineer
Front-end engineers work closely with designers to make websites beautiful, functional, and fast.Includes 34 CoursesWith Professional CertificationBeginner Friendly115 hours - Free course
Learn JavaScript
Learn how to use JavaScript — a powerful and flexible programming language for adding website interactivity.Beginner Friendly15 hours