getElementById Method in JavaScript
The getElementById method in JavaScript is used to access a specific HTML element by its ID. It is one of the most commonly used methods for manipulating HTML elements, allowing developers to dynamically change content, styles, and attributes of elements on the web page.
Key Features of the getElementById Method:
- getElementById is a method of the Document Object that allows you to access elements by their unique ID.
- Using getElementById, you can retrieve a single element on the page, as IDs are unique within a document.
- This method is case-sensitive, meaning it only recognizes IDs exactly as they are written in the HTML.
- Once an element is retrieved, you can modify its content, style, attributes, or even add event listeners to it.
This example shows how to change the text content of an element using getElementById:
Syntax of getElementById Method:
document.getElementById("elementID");
Example 1: Changing Text Content
This example shows how to change the text content of an element using getElementById:
Example
ocument.getElementById("demo").innerHTML = "Hello, World!";
Output
Example 2: Changing Styles
In this example, we change the style of an element with a specific ID using getElementById:
Example
document.getElementById("demo").style.color = "red";
document.getElementById("demo").style.fontSize = "24px";
Output
Example 3: Modifying Attributes
This example demonstrates how to change an attribute of an HTML element, such as an image's source:
Example
document.getElementById("myImage").src = "new_image.jpg";
Output
Example 4: Adding Event Listeners
In this example, we use getElementById to attach a click event listener to a button:
Example
document.getElementById("myButton").addEventListener("click", function() {
alert("Button clicked!");
});