Visit Mozilla.org

DOM:document.getElementById

From MDC

« Gecko DOM Reference

Contents

[edit] Summary

Returns the element whose ID is specified.

[edit] 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.

[edit] 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>

[edit] 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!

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

[edit] Specification