How to use getElementById method In Javascript

JavaScript hase getElementById method to access and retrieve a reference to an HTML element by its unique identifier. This method enables dynamic interaction with the Document Object Model (DOM) by allowing direct manipulation of specific elements on a web page.

Syntax:

let element = document.getElementById("myElement");

Example: To demonstrate selecting an HTML element by ID in JavaScript and then using it for updating the state of another HTML element.

HTML




<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width,
                                   initial-scale=1.0" />
    <title>Selecting by ID in JavaScript</title>
  </head>
  <body>
    <div style="margin: 80px">
      <h1 id="myElement">Hello, World!</h1>
      <button onclick="changeColor()">Change Color</button>
    </div>
 
    <script>
      function changeColor() {
        // Selecting element by ID
        let element = document.getElementById("myElement");
 
        // Manipulating the selected element
        element.style.color = "red";
      }
    </script>
  </body>
</html>


Output:

How to Select an Element by ID in JavaScript ?

In JavaScript, we can use the “id” attribute to interact with HTML elements. The “id” attribute in HTML assigns a unique identifier to an element. This uniqueness makes it easy for JavaScript to precisely target and manipulate specific elements on a webpage. Selecting elements by ID helps in dynamic content updates, event handling, and DOM manipulation.

Table of Content

  • Using getElementById Method
  • Using the query selector method

Similar Reads

Using getElementById method

JavaScript hase getElementById method to access and retrieve a reference to an HTML element by its unique identifier. This method enables dynamic interaction with the Document Object Model (DOM) by allowing direct manipulation of specific elements on a web page....

Using the query selector method

...