Computer >> Computer tutorials >  >> Programming >> Javascript

How getElementByID works in JavaScript?


getElementById

The getElementById() is a DOM method used to return the element that has the ID attribute with the specified value. This is one of the most common methods in the HTML DOM and is used almost every time we want to manipulate an element on our document. This method returns null if no elements with the specified ID exists. The ID should be unique within a page. However, if more than one element with the specified ID exists, it returns the last element in the javascript code.

Example-1

In the following example, there exists a paragraph tag with the inner text "GetElementById" and with an id called "element". Using the DOM method "document.getElementById()" the text inside the paragraph tag is accessed and the value is displayed in the output. Without ".innerHtml" the document.getElementById can't read the inner text part of any tag.

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

Output

GetElementById
GetElementById

Example-2

In the following example, using the DOM method "getElementById" we have replaced the original text part "GetElementById" with the text "Tutorix" and the result is displayed in the output.

<html>
<body>
<p id="element">GetElementById</p>
<script>
   document.getElementById("element").innerHTML = "Tutorix";
</script>
</body>
</html>

Output

Tutorix