HTML DOM getElementById() Method

Definition and Usage

The getElementById() method returns a reference to the first object with the specified ID.

Syntax

document.getElementById(id)

Description

The HTML DOM defines multiple methods for finding elements, in addition to getElementById(), including getElementsByName() and getElementsByTagName().

However, if you need to find a specific element in a document, the most effective method is getElementById().

When operating a specific element of a document, it is best to give the element an id attribute, specify a unique name for it (in the document), and then you can use the ID to find the desired element.

Example

Example 1

<html>
<head>
<script type="text/javascript">
function getValue()
  
  var x=document.getElementById("myHeader")
  alert(x.innerHTML)
  



<h1 id="myHeader" onclick="getValue()">This is a header</h1>
<p>Click on the header to alert its value</p>

Example 2

getElementById() is an important method, and its use is very common in DOM programming. We have defined a utility function for you so that you can use the getElementById() method with a shorter name:

function id(x) {
  if (typeof x == "string") return document.getElementById(x)
  return x;
  

This function accepts element ID as their parameter. For each such parameter, you can write x = id(x) before using it.

Try It Yourself (TIY)

Use getElementById()