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:

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

The content of the element with ID "demo" changes to "Hello, World!".

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

The text color of the element with ID "demo" changes to red, and the font size is set to 24px.

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

The source of the image element with ID "myImage" changes to "new_image.jpg".

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!");
            });

Output

When the button with ID "myButton" is clicked, an alert box displays with the message "Button clicked!".