Home>Tutorial>
JavaScript document.getElementById and Examples
Nuelson Penuel
Sunday, July 23, 2023
Javascript
The document.getElementById() method in JavaScript is used to retrieve an HTML element on a webpage by its unique ID. It returns a reference to the element as an object or null if no element is found with the specified ID. Here's a detailed explanation of how it works and examples of its usage:
The syntax for document.getElementById() is:
document.getElementById("elementID");
The method takes a single parameter, which is the ID of the HTML element you want to select. The ID is specified as a string enclosed in quotes.
Example 1: Selecting an HTML element and modifying its content:
HTML:
<div id="myElement">Hello, World!</div>
JavaScript:
var element = document.getElementById("myElement");
element.innerHTML = "Hello, JavaScript!";
In this example, the getElementById() method is used to select the
element with the ID "myElement". It then modifies the innerHTML property of the element to replace the "Hello, World!" text with "Hello, JavaScript!".
Example 2: Changing the CSS style of an HTML element:
HTML:
<div id="myElement">Hello, World!</div>
JavaScript:
var element = document.getElementById("myElement");
element.style.color = "red";
element.style.fontSize = "20px";
In this example, the getElementById() method is used to select the
element with the ID "myElement". It then modifies the CSS styles of the element by accessing the style property and setting specific style properties like color and fontSize.
Example 3: Adding an event listener to an HTML element:
HTML:
<button id="myButton">Click Me!</button>
JavaScript:
var button = document.getElementById("myButton");
button.addEventListener("click", function() {
console.log("Button clicked!");
});
In this example, the getElementById() method is used to select the button element with the ID "myButton". It then adds an event listener to the button that listens for a click event. When the button is clicked, the provided callback function is executed, which, in this case, logs a message to the console.
Overall, the document.getElementById() method is an essential tool to manipulate and interact with HTML elements on a webpage. It allows developers to select elements by their unique IDs and perform various operations on them, such as modifying their content, changing their styles, or attaching event listeners.
Up Vote(0) |
Down Vote(0 |
Views(197)
See Demo |
Download File
Emmason Integratded Services(2017-2024)
All Rights Reserved
Designed and Maintained By Emmason Integrated Services
.