JavaScript – Finding Elements with getElementById

Finding Elements with getElementById()
JavaScript uses document.getElementById() to find specific elements on the page so you can read or change them.
W3Schools: getElementById()

Basic Idea
Give the element an id in your HTML, then use that id in JavaScript.

Example:

<p id="message">Hello</p>
<script>
let msg = document.getElementById("message");
</script>

Check Your Work in the Console (Ctrl+Shift+I or F12)
After the page loads, open the console and type:
msg
If everything is correct, the console will show the <p> element.
You can also type:
msg.innerHTML
This prints the text inside the element (“Hello”).

Common Error: Misspelled Id
If the id in JavaScript does not match the id in HTML exactly, the variable becomes null.

Example mistake:

<p id="message">Hello</p>
<script>
let msg = document.getElementById("mesage"); // typo in id
</script>

Now typing msg in the console shows null.
Typing msg.innerHTML will cause an error because you cannot access a property of null.
If you see null, check the spelling of the id in both locations.

Why This Matters
Once your JavaScript has the element, you can change text (innerHTML), read input (value), swap images (src), or modify styles (style.color, style.display, etc.).
Those specific actions appear on the next pages.


This page was created by ChatGPT with guidance, editorial scrutiny, and approval of the human creator of this website.