Delicious Bookmark this on Delicious Share on Facebook SlashdotSlashdot It! Digg! Digg

DOM document.getElementById


Returns the element whose ID is specified.


element = document.getElementById(id);


  • element is an element object.
  • id is a case-sensitive string representing the unique ID of the element being sought.


<title>getElementById example</title>

<script type="text/javascript">

function changeColor(newColor)
 elem = document.getElementById("para1"); = newColor;

<p id="para1">Some text here</p>
<button onclick="changeColor('blue');">blue</button>
<button onclick="changeColor('red');">red</button>


If there is no element with the given id, this function returns null. Note also that the DOM implementation must have information that says which attributes are of type ID. Attributes with the name "id" are not of type ID unless so defined in the document's DTD. The id attribute is defined to be of ID type in the common cases of XHTML, XUL, and other. Implementations that do not know whether attributes are of type ID or not are expected to return null.

Simply creating an element and assigning an ID will not make the element accessible by getElementById. Instead one needs to insert the element first into the document tree with insertBefore or a similar method, probably into a hidden div.

var element = document.createElement("div"); = 'testqq';
var el = document.getElementById('testqq'); // el will be null!

New users should note that the capitalization of 'Id' must be correct for the code to function - 'getElementByID' does not work, however natural it may seem.

getElementById was introduced in DOM Level 1 for HTML documents and moved to all documents in DOM Level 2.


Free   Version: n/a   Platform(s): All   Updated:  August 5, 2008

Developer:EPSYLONSYS Demo Download  
Rated by: 1 user(s)  
Follow Navioo On Twitter

Submit a resource