HTML DOM getElementById() method

HTMLWeb DevelopmentFront End Technology

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.


Following is the syntax for getElementById() method −



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

<!DOCTYPE html>
   function changeLink() {
      var l = document.getElementById("LINK1"); = "red";"40px";
<h1>getElementById() example</h1>
<a id="LINK1" href="">GOOGLE</a>
<p>Click the below button to apply styling to the above link</p>
<button onclick="changeLink()">CHANGE</button>


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 “”.

<a id="LINK1" href="">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"); = "red";"40px";
Published on 09-Aug-2019 11:46:23