How Document.getElementById() Works

Posted by

document.getElementById() is a method that is used to get an element from an HTML document based on its id. It returns the element as an object, which you can then manipulate with JavaScript.

Here’s an example of how to use document.getElementById() in action:

[dm_code_snippet background=”yes” background-mobile=”yes” slim=”no” line-numbers=”no” bg-color=”#abb8c3″ theme=”dark” language=”javascript” wrapped=”no” height=”” copy-text=”Copy Code” copy-confirmed=”Copied”]

<!DOCTYPE html>
<html>
<body>
  <p id="myParagraph">This is a paragraph.</p>
  <script>
    // Get the element with the id "myId"
    var element = document.getElementById("myId");
    // Change the text of the element
    element.innerHTML = "This is a new paragraph.";
  </script>
</body>
</html>

[/dm_code_snippet]

In this example, the element with the id “myId” is a p element that contains the text “This is a paragraph.” The JavaScript code gets a reference to this element using document.getElementById() and then changes the text of the element by setting the innerHTML property to a new value.

You can use document.getElementById() to get any element on an HTML page as long as the element has an id attribute. You can then use various properties and methods of the element object to manipulate the element.