How to use getElementById() in Javascript
By Tan Lee Published on Dec 18, 2024 217
The `getElementById()` method in JavaScript is used to select and retrieve an HTML element with a specified `id` attribute.
Here's an example of how to use getElementById()
in JavaScript:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>getElementById Example</title> </head> <body> <h1 id="greeting">Hello, World!</h1> <button onclick="changeText()">Click me</button> <script> function changeText() { // Use getElementById to select the element with id "greeting" var greetingElement = document.getElementById("greeting"); // Change the text content of the selected element greetingElement.textContent = "Hello, JavaScript!"; } </script> </body> </html>
The textContent
property sets or returns the text content of the specified node and all its descendants.
In this example, the getElementById("greeting")
method selects the <h1>
element with the ID "greeting", and the changeText()
function changes its text content when the button is clicked.
- How to use sweetalert2
- How to Pass string parameter in an onclick function
- How to format number with commas and decimal in Javascript
- What does 'use strict;' means in Javascript
- How to detect if caps lock is pressed in Javascript
- How to create a Custom Event in Javascript
- How to Check if an Object Has a Property Properly in JavaScript
- How to convert an Uint8Array to string in Javascript
Categories
Popular Posts
11 Things You Didn't Know About Cloudflare
Dec 19, 2024
Portal HTML Bootstrap
Nov 13, 2024
Modernize Material UI Admin Dashboard Template
Nov 19, 2024