Javascript – document.getElementById() method

The document.getElementById() method returns the element of specified id.

The getElementById() is a DOM (Document Object Model) method.

This method returns null if no elements with the specified ID exists.

The ID should be unique within a page.

If more than one element with the specified ID exists, the getElementById() method returns the first one it encounters.

Syntax

document.getElementById(elementID)

Parameter Values

ParameterTypeDescription
elementIDStringRequired. It is the ID attribute’s value of the element you want to get.
document.getElementById() Parameter Values

Example

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Javascript - document.getElementById() method example</title>
</head>

<body>
    <p id="element">GetElementById</p>
    <script>
        var s = document.getElementById("element").innerHTML;
        document.write(s);
    </script>
</body>

</html>
  • In the above example, there is a paragraph tag with the inner text “GetElementById” and with an id called “element”.
  • “document.getElementById()” method is used to access the text inside the paragraph tag and the value is displayed in the output.
  • “.innerHtml” is used to read the inner text part of any tag.

The id is case-sensitive. For example, the 'root' and 'Root' are totally different id.