The JavaScript getElementById() method is used to find an HTML element by its unique id attribute. It is one of the most common DOM methods because it lets you select a specific element and then read or change its content, style, attributes, or behavior.
1. What Is getElementById() in JavaScript?
getElementById() is a method of the browser’s document object. It searches the document for an element whose id matches the supplied string and returns that element.
Every ID should be unique within an HTML document. If an element with the specified ID does not exist, the method returns null.
2. getElementById() Syntax
document.getElementById(elementId);
Parameter: elementId is a case-sensitive string containing the ID to find. Do not include the # symbol used by CSS ID selectors.
Return value: The matching Element object, or null if no matching element is found.
3. Basic getElementById() Example
In this example, JavaScript selects a heading with the ID title and displays its text in the browser console.
<h1 id="title">Welcome to JavaScript</h1>
<script>
const heading = document.getElementById("title");
console.log(heading);
console.log(heading.textContent);
</script>
The method returns the heading element. Its textContent property contains the text inside that element.
4. Change HTML Content Using getElementById()
After selecting an element, you can update its text with the textContent property. This is a common way to change page content dynamically.
<p id="message">Old message</p>
<script>
const message = document.getElementById("message");
message.textContent = "Hello! Content updated with JavaScript.";
</script>
Use textContent when you want to insert plain text. If you use innerHTML to parse HTML markup, only assign trusted or properly sanitized content. Never place untrusted user input directly into innerHTML, because it can introduce cross-site scripting (XSS) vulnerabilities.
5. Change CSS Style Using getElementById()
The selected element’s style property allows you to update its inline CSS styles through JavaScript.
<h2 id="heading">JavaScript DOM Tutorial</h2>
<script>
const heading = document.getElementById("heading");
heading.style.color = "blue";
heading.style.backgroundColor = "lightyellow";
heading.style.fontSize = "30px";
</script>
Notice that CSS property names containing hyphens use camelCase in JavaScript. For example, background-color becomes backgroundColor.
6. Get and Change HTML Attributes
You can use getElementById() to select an element and then work with its attributes using methods such as getAttribute(), setAttribute(), and removeAttribute().
<img id="productImage" src="old-product.jpg" alt="Old product">
<script>
const image = document.getElementById("productImage");
console.log(image.getAttribute("src"));
image.setAttribute("src", "new-product.jpg");
image.setAttribute("alt", "New product image");
</script>
The image source and alternative text are updated after the element is selected.
7. Add a Click Event with getElementById()
The method is often used to select buttons and attach event listeners. The following example changes a paragraph when the user clicks a button.
<button id="showButton">Click Me</button>
<p id="output">Waiting for a click...</p>
<script>
const button = document.getElementById("showButton");
const output = document.getElementById("output");
button.addEventListener("click", function() {
output.textContent = "Button clicked successfully!";
});
</script>
addEventListener() registers a callback that runs when the button receives a click event. It is generally preferable to using inline HTML event-handler attributes.
8. Check Whether an Element Exists
If an ID is not found, getElementById() returns null. Check the result before accessing properties or calling methods to avoid errors.
const element = document.getElementById("userName");
if (element !== null) {
element.textContent = "Welcome, user!";
} else {
console.log("Element was not found.");
}
You can also use a concise truthiness check:
const element = document.getElementById("userName");
if (element) {
element.textContent = "Welcome!";
}
9. getElementById() Is Case-Sensitive
The ID string passed to getElementById() must match the element’s ID exactly, including letter case.
<h1 id="pageTitle">My Website</h1>
<script>
console.log(document.getElementById("pageTitle")); // Element
console.log(document.getElementById("pagetitle")); // null
console.log(document.getElementById("PageTitle")); // null
</script>
Here, pageTitle, pagetitle, and PageTitle are different strings.
10. Do Not Include the # Symbol
Unlike querySelector(), getElementById() expects the ID value without a hash symbol.
<div id="content">Page content</div>
<script>
// Correct
const content = document.getElementById("content");
// Incorrect: this normally returns null
const wrong = document.getElementById("#content");
// CSS selector syntax with querySelector()
const alsoCorrect = document.querySelector("#content");
</script>
Use document.getElementById("content") for the ID method, but use document.querySelector("#content") when passing a CSS ID selector.
11. getElementById() vs querySelector()
Both methods can select an element by ID, but their arguments and capabilities are different.
| Feature | getElementById() | querySelector() |
|---|---|---|
| Argument | ID value without # | CSS selector |
| Example | getElementById(“box”) | querySelector(“#box”) |
| Selector support | ID lookup only | Any valid CSS selector |
| Return value | Element or null | First matching element or null |
| Availability | Document method | Available on Document and Element |
For a direct ID lookup in the document, getElementById() is clear and convenient. Use querySelector() when you need a CSS selector or want to search within a particular element.
