Dom bom
getElementById Method
In this tutorial, we will learn about the getElementById method in JavaScript.
In JavaScript, the getElementById() method is used to get the element with the specified ID from the document. It is a method of the document object that allows you to access and manipulate elements in the HTML document by their ID.
Syntax
The syntax for the getElementById() method is as follows:
let element = document.getElementById(id);Where:
- idis a string that specifies the ID of the element you want to get.
- elementis the element with the specified ID, or- nullif no element is found.
Example
Suppose you have the following HTML document:
<!doctype html>
<html>
  <head>
    <title>Get Element By ID Example</title>
  </head>
  <body>
    <h1 id="heading">Hello, World!</h1>
    <script src="main.js"></script>
  </body>
</html>You can use the getElementById() method to get the element with the ID heading and change its content:
let element = document.getElementById("heading");
element.innerHTML = "Goodbye, World!";This will change the content of the <h1> element to "Goodbye, World!".
Conclusion
- The getElementById()method is used to get the element with the specified ID from the document.
- It is a method of the documentobject that allows you to access and manipulate elements in the HTML document by their ID.
- The method returns the element with the specified ID, or nullif no element is found.
- You can use the getElementById()method to access and manipulate elements in the HTML document by their ID.
How is this guide?
Sign in to share your feedback
Help us improve by sharing your thoughts on this guide.
Last updated on