HTML DOM getElementById() method


The HTML DOM getElementById() method is used for returning an element by passing an id as a parameter to this function. It is one of the most commonly used and easiest method for getting elements to manipulate later. If the specified Id doesn’t exist, it returns NULL.

Syntax

Following is the syntax for getElementById() method −

document.getElementById(elementID)

Example

Let us look at an example for the getElementById() method −

<!DOCTYPE html>
<html>
<head>
<script>
   function changeLink() {
      var l = document.getElementById("LINK1");
      l.style.color = "red";
      l.style.fontSize="40px";
   }
</script>
</head>
<body>
<h1>getElementById() example</h1>
<a id="LINK1" href="https://www.google.com">GOOGLE</a>
<p>Click the below button to apply styling to the above link</p>
<button onclick="changeLink()">CHANGE</button>
</body>
</html>

Output

This will produce the following output −

On clicking the CHANGE button −

In the above example −

We have first created an anchor element with id “LINK1” and href attribute value set to “https://www.google.com”.

<a id="LINK1" href="https://www.google.com">GOOGLE</a>

We have then created a button CHANGE that will execute the changeLink() when clicked by the user −

<button onclick="changeLink()">CHANGE</button>

The changeLink() method gets the <a> element using the document object getElementById() method and passing the <a> element id as parameter. It then returns the element which we assign to variable l. Using the global style attribute we set the color and fontSize property value for the anchor tag −

function changeLink() {
   var l = document.getElementById("LINK1");
   l.style.color = "red";
   l.style.fontSize="40px";
}

Updated on: 23-Nov-2023

920 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements