How to use getElementById() in Javascript
By FoxLearn 12/18/2024 7:11:00 AM 11
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.
Categories
Popular Posts
11 Things You Didn't Know About Cloudflare
12/19/2024