How to use getElementById() in Javascript
By FoxLearn 12/18/2024 7:11:00 AM 141
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.
- 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
- How to copy text to clipboard in Javascript
- How to Pass string parameter in an onclick function
- How to convert voice to text in Javascript
Categories
Popular Posts
Portal HTML Bootstrap
11/14/2024
Gentella Admin Template
11/14/2024
Material Lite Admin Template
11/14/2024
Carpatin Admin Dashboard Template
11/17/2024