Collapse the table of content
Expand the table of content

getElementById method

Returns a reference to the first object with the specified value of the ID or NAME attribute.

Document Object Model (DOM) Level 3 Core Specification, Section 1.4



var retval = document.getElementById(v);


v [in]

Type: BSTR

A String that specifies the ID value. Case-insensitive.

Return value

Type: IHTMLElement

Returns the first object with the specified ID or null if there is no match.

Standards information


If more than one element is found, getElementById returns the first object in the collection.

Windows Internet Explorer 8 and later. In IE8 Standards mode, getElementById performs a case-sensitive match on the ID attribute only. In IE7 Standards mode and previous modes, this method performs a case-insensitive match on both the ID and NAME attributes, which might produce unexpected results. For more information, see Defining Document Compatibility.

Internet Explorer 8 or later. An alternate implementation is available. For more information, see getElementById.


The following example uses getElementById to display the content of the first div element in a collection with the ID attribute value, oDiv1, when a button is clicked.

<!DOCTYPE html>

  <title>Show First DIV Content</title>
  <meta content="text/html; charset=utf-8" http-equiv="Content-Type">
  <meta http-equiv="X-UA-Compatible" content="IE=8">

  <div id="oDiv1">Div #1</div>
  <div id="oDiv2">Div #2</div>
  <div id="oDiv3">Div #3</div>
  <input type="button" value="Show First DIV Content" onclick="fnGetId()"> 
  <script type="text/javascript">
    function fnGetId() {
      // Display the content of the first DIV element in the collection.
      var oVDiv=document.getElementById("oDiv1");
      alert("The content of the first DIV element is " + "\"" + oVDiv.innerHTML + "\".");


See also

About the W3C Document Object Model



© 2015 Microsoft