In JavaScript, the getElementById method is used to retrieve an HTML element from the DOM (Document Object Model) based on its unique ID attribute. Here’s how it works:
Syntax
var element = document.getElementById(id);
Parameters
id: This is a string parameter that represents the unique ID attribute of the HTML element you want to retrieve.
Return Values
It returns a reference to the HTML element with the specified ID. If no element with the given ID exists, it returns null.
Usage
Once you have the reference to the element, you can manipulate it in various ways, such as changing its content, style, or behavior.
Example
Example
Hello, world!
JavaScript (script.js
):
// Retrieving the element with id "myDiv"
var element = document.getElementById("myDiv");
// Manipulating the element
element.innerHTML = "Goodbye, world!";
element.style.color = "red";
In this example, the JavaScript code retrieves the div element with the ID “myDiv”, then changes its content to “Goodbye, world!” and its text color to red.
Keep in mind that IDs should be unique within the HTML document. If multiple elements have the same ID, getElementById will only return the first matching element. Also, note that the method is case-sensitive.