JavaScript: getElementById
getElementById() finds the element whose id matches a string, so a script can read or update that element.
What you will learn
- How an HTML id connects to JavaScript
- How to update text with
textContent - Why a missing element returns
null
Minimal example
<p id="message">Waiting...</p>
<script>
const message = document.getElementById('message');
if (message) message.textContent = 'Ready';
</script>The id should be unique in the document. Use textContent for plain text so a value is not interpreted as HTML.
Common mistakes
- Call the code after the element exists, such as after the script at the end of the body or
DOMContentLoaded. - Check for
nullwhen the element may not be present. - Do not reuse an id for several elements; use a class or a selector when you need a collection.