JAVASCRIPT » Snippets

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

DOM document.getElementById


Summary

Returns the element whose ID is specified.

Syntax

element = document.getElementById(id);

where

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

Example

<html>
<head>
<title>getElementById example</title>

<script type="text/javascript">

function changeColor(newColor)
{
 elem = document.getElementById("para1");
 elem.style.color = newColor;
}
</script>
</head>

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

Notes

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");
element.id = '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.

Specification


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