Key takeaways:
The getElementById()
method in JavaScript allows us to directly access and manipulate individual elements in an HTML document by their unique id
.
We can use it with this syntax: document.getElementById("elementID")
The method accepts a single parameter—the ID of the element—and returns the corresponding element.
If the specified ID does not exist, getElementById()
returns null
, which is helpful for checking if the element exists before applying changes.
Imagine we want to change the text of a specific heading or modify the color of a button when it’s clicked. How can we pinpoint that exact element in our code? JavaScript’s getElementById()
method is a straightforward way to access and manipulate individual elements within the DOM by using their unique IDs. Let’s dive in to understand how this works.
What is getElementById()
?
The getElementById()
method is a part of the JavaScript Document Object Model (DOM) that allows us to access an HTML element with a specified ID. When we use getElementById()
, JavaScript scans the document and returns the element with the matching ID. This method is frequently used to manipulate specific elements by changing their styles, content, or attributes. The name of the id
is passed as a parameter, and the corresponding element is the return value.
Syntax
The syntax for getElementById()
is simple: