JavaScript – getElementById()
JavaScript getElementById() is a DOM method used to access one HTML element by its unique id value. It is commonly used when you want to read text, change content, update styles, set form values, attach events, or work with a specific element on a web page.
To access an HTML DOM element with the help of its id value, use document.getElementById(<id_value>). The method searches the document for an element whose id matches the string you provide and returns that element object. If no matching element exists, it returns null.
document.getElementById() syntax for selecting an element by id
The syntax of getElementById() function is
document.getElementById(id_value)
In html,
<htmlTag id="id_value">
</htmlTag>
htmlTag could be any html tag. For example : html, body, div, h1, h2, h3, p, img, a, etc.
Note: Please observe the casing in the function name, getElementById. During the initial stages, beginners might type it incorrectly.
As id is maintained uniquely for HTML DOM elements, document.getElementById() function returns object of only one element whose id matches.
If it doesn’t find an HTML DOM element with the specified id, null is returned.
In practical JavaScript code, write the id as a string and do not include the CSS # symbol. For example, use document.getElementById("message"), not document.getElementById("#message").
How the HTML id attribute connects to getElementById()
The id attribute gives an HTML element a unique name inside the page. JavaScript can then use that name to select the element directly. A valid page should not contain multiple elements with the same id, because duplicate ids make scripts, styles, labels, and links harder to predict.
<h2 id="page-title">Products</h2>
<p id="description">Product list is loading.</p>
<button id="refresh-button">Refresh</button>
Each element above can be selected by passing only its id value to getElementById().
const title = document.getElementById("page-title");
const description = document.getElementById("description");
const refreshButton = document.getElementById("refresh-button");
Return value of document.getElementById(): element object or null
document.getElementById() returns an Element object when a matching id is found. If the id is not present in the document at the time the line runs, the return value is null. This is important because trying to change a property on null causes an error.
const message = document.getElementById("message");
if (message !== null) {
message.textContent = "Message element found.";
}
The null check is useful when an element appears only on some pages, when HTML is generated conditionally, or when the script may run before the element has been loaded.
JavaScript getElementById() example that changes paragraph content
In the following example, we shall access an HTML DOM element, a paragraph with id=”message” and modify its content.
index.html
<!doctype html>
<html>
<body>
<h1>JavaScript getElementById() Example</h1>
<p id="message"></p>
<script>
var messageElement = document.getElementById("message");
messageElement.innerHTML = "This is how we access an HTML DOM element using its id value.";
</script>
</body>
</html>
The paragraph starts empty. The script selects the paragraph using document.getElementById("message") and then assigns new content to its innerHTML property.
Changing text safely with getElementById() and textContent
When you only need to set plain text, textContent is usually more suitable than innerHTML. The innerHTML property parses the assigned string as HTML, while textContent treats it as text.
<p id="status">Waiting...</p>
<script>
const statusElement = document.getElementById("status");
statusElement.textContent = "Form submitted successfully.";
</script>
Use innerHTML when you intentionally want to insert HTML markup. Use textContent when the value is plain text or may come from user input.
Updating styles and form values using getElementById()
After selecting an element by id, you can access and change its DOM properties. The exact property depends on the element type. For a paragraph, you might change textContent or style. For an input field, you often change value.
<input id="username" type="text">
<p id="help-text">Enter your username.</p>
<script>
const username = document.getElementById("username");
const helpText = document.getElementById("help-text");
username.value = "guest";
helpText.style.fontWeight = "bold";
</script>
This example selects two different elements. The input field is updated through value, and the paragraph style is updated through the element’s style object.
Running getElementById() after the HTML element exists
A common reason for getElementById() returning null is that the script runs before the browser has created the element in the DOM. You can avoid this by placing the script after the HTML element, using the defer attribute on an external script, or running code after the DOMContentLoaded event.
<p id="notice">Old text</p>
<script>
const notice = document.getElementById("notice");
notice.textContent = "New text";
</script>
For external JavaScript files, defer is a clean option because it downloads the script without blocking parsing and runs it after the HTML document has been parsed.
<script src="app.js" defer></script>
getElementById() vs querySelector(‘#id’) in JavaScript
Both document.getElementById("message") and document.querySelector("#message") can select an element by id. The difference is in what each method accepts.
| Method | What you pass | Best use |
|---|---|---|
getElementById("message") | The id value only, without # | Selecting one element by its id |
querySelector("#message") | A CSS selector | Selecting by id, class, attribute, nested selector, or other CSS selector |
When you already know the exact id, getElementById() is direct and easy to read. When you need a CSS selector such as ".card.active", "form input[name='email']", or "#menu li:first-child", use querySelector().
Common JavaScript getElementById() mistakes and fixes
- Using # inside getElementById: write
document.getElementById("title"), notdocument.getElementById("#title"). - Typing the method name with wrong casing: JavaScript is case-sensitive, so
getElementByIdmust be typed exactly. - Running the script too early: place the script after the element, use
defer, or wait forDOMContentLoaded. - Using duplicate ids: keep ids unique so JavaScript, CSS, labels, and links refer to the intended element.
- Changing plain text with innerHTML: prefer
textContentwhen you do not need to insert HTML markup.
FAQs on JavaScript document.getElementById()
1. When should I use document.getElementById()?
Use document.getElementById() when you need to select one specific element and that element has a unique id attribute. It is a good fit for changing a message area, reading an input, attaching an event to a known button, or updating a single section of a page.
2. Is getElementById() better than querySelector()?
Neither method is always better. Use getElementById() for direct id lookup. Use querySelector() when you need CSS selector features such as class selectors, attribute selectors, descendant selectors, or pseudo-class selectors.
3. Why does document.getElementById() return null?
It returns null when the document does not contain an element with the specified id at the time the code runs. Check the id spelling, remove the # symbol if you used it, and make sure the script runs after the element has been parsed.
4. Can getElementById() select multiple elements?
No. getElementById() returns a single element object or null. If you need to select multiple elements, use methods such as querySelectorAll(), getElementsByClassName(), or getElementsByTagName(), depending on the selection you need.
5. Should I use innerHTML or textContent after getElementById()?
Use textContent for plain text. Use innerHTML only when the assigned string is intended to contain HTML markup and you trust or safely control that markup.
Editorial QA checklist for this getElementById() tutorial
- Confirms that
getElementById()receives the id value without the#symbol. - Explains that the method returns one element object or
null. - Warns about duplicate HTML ids and script timing issues.
- Shows both
innerHTMLandtextContentuse cases without treating them as identical. - Compares
getElementById()withquerySelector()in a beginner-friendly way.
Summary of JavaScript getElementById()
document.getElementById() is used to select a single HTML element by its id. Pass the id as a string without #, make sure the id is unique, and check for null when the element may not exist. Once the element is selected, you can update its text, HTML, styles, value, or event handlers based on the needs of the page.
In this JavaScript Tutorial, we have learnt how to access an HTML DOM element using its id, and change its innerhtml text.
TutorialKart.com