getElementById ExamplesΒΆ

The general syntax for this method is:

let element = document.getElementById("element-id");

Searches the HTML document for an element that has an id attribute that matches the string parameter. Returns a reference to the matching element object if match found. If NO matching element is found, null is returned.

Example

 1<!DOCTYPE html>
 2<html>
 3   <head>
 4      <title>DOM Examples</title>
 5   </head>
 6   <body>
 7      <h1>getElementById Example</h1>
 8      <p id="description">
 9         This will be turned blue.
10      </p>
11      <script>
12         let paragraph = document.getElementById("description");
13         console.log("paragraph contents:", paragraph.innerHTML.trim());
14         paragraph.style.color = "blue";
15      </script>
16   </body>
17</html>

Console Output

paragraph contents: This will be turned blue.

Tip

Because getElementById returns null if an element with a matching id can NOT be found, you could see a message like TypeError: paragraph is null. Be sure to double check the id you are using in JavaScript and in the HTML.