What is the purpose of the “document.getElementById” function in JavaScript?

The document.getElementById function in JavaScript is used to get the reference of an HTML element. The id attribute is a unique attribute that you can use to style your HTML element using CSS or you can use it to manipulate your HTML element or its content.

HTML
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Separate HTML and JavaScript</title>
</head>
<body>

  <h1 id="demo">Original Content</h1>
  
  <script src="script.js"></script>
</body>
</html>
JavaScript
// Get the element with the ID "demo"
var element = document.getElementById("demo");

// Change the content
element.innerHTML = "New Content";

In this example I m manipulating the content of the HTML element by taking its reference using its id.

Leave a Reply

Your email address will not be published. Required fields are marked *