Methods


getElementById Method

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

Syntax

oElement = object.getElementById(sIDValue)

Parameters

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

Return Value

Returns the first object with the specified ID or NAME.

Remarks

 New for Windows Internet Explorer 8 Internet Explorer 8 and later. In IE8 mode, getElementById performs a case-sensitive match on the ID attribute only. In IE7 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.

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

Example

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 PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <title>"Show First DIV Content"</title>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" >
  <meta http-equiv="X-UA-Compatible" content="IE=8">

<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 + "\".");
}
</script>

</head>

<body>
  <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()"> 
</body>

</html>

Standards Information

This method is defined in World Wide Web Consortium (W3C) Document Object Model (DOM) Level 1 World Wide Web link.

Applies To

document, HTMLDocument Constructor

See Also

About the W3C Document Object Model
Tags : html


Community Content

John Sudds
Doesn't work with anchors...

This doesn't seem to return anchors properly. That is, on an HTML page with the following in the body:

<p>Here is an anchor:
<br><a id="blar"></a>Blar
</p>

the following javascript returns nothing:

document.onload = alert(document.getElementById('blar'));

This is a sorry state of affairs, is it not?

-- It certainly might be, if the code were doing what you think it is. However, you have a few errors:

  • The alert statement itself must be inside a function block; otherwise, you are assigning the return value of the call to the event handler.
  • The onload event handler is on the window object, not the document object.

Here is the correct code, which returns the anticipated value of "[object]":

window.onload = function() 
{
alert(typeof(document.getElementById('blar')));
}

(jsudds)


Noelle Mallory - MSFT
Be Careful! - This method also incorrectly matches on the NAME attribute

It should be noted, that this method also matches on the name attribute, thus if you had say:

<meta name="description" content="matching on this is a bug"/>

<!-- All your code... -->

<textarea name="description" id="description">This is information about the bug</textarea>

In W3C compliant browsers, document.getElementById('description'); would match on the form field, not the meta tag!!!


Stanley Roark
Workaround to make document.getElementById() follow W3C standard and only match on id

You can make Internet Explorer's document.getElementById() method work according to W3C standards and only return elements with matching id and not name by overriding the native function in JavaScript like this:

if (/msie/i.test (navigator.userAgent)) //only override IE
{
document.nativeGetElementById = document.getElementById;
document.getElementById = function(id)
{
var elem = document.nativeGetElementById(id);
if(elem)
{
//make sure that it is a valid match on id
if(elem.attributes['id'].value == id)
{
return elem;
}
else
{
//otherwise find the correct element
for(var i=1;i<document.all[id].length;i++)
{
if(document.all[id][i].attributes['id'].value == id)
{
return document.all[id][i];
}
}
}
}
return null;
}
}

Workaround attributed to http://webbugtrack.blogspot.com/2007/08/bug-152-getelementbyid-returns.html
Workaround revised to work around a different error in IE's implementation of getAttribute() see:
http://www.sixteensmallstones.org/ie-javascript-bugs-overriding-internet-explorers-documentgetelementbyid-to-be-w3c-compliant-exposes-an-additional-bug-in-getattributes


arnoschaefer
Undocumented restriction or bug
This method will return an error if the ID attribute provided to the method is identical to the name of a variable or a function being used in the javascript code.

This will generate the message "Object doesn't support this property or method"

<SCRIPT>
function fnGetId(){
   // Returns the first DIV element in the collection.
   var oDiv1=document.getElementById("oDiv1");
}
</SCRIPT>
<DIV ID="oDiv1">Div #1</DIV>
<DIV ID="oDiv2">Div #2</DIV>
<DIV ID="oDiv3">Div #3</DIV>
<INPUT TYPE="button" VALUE="Get Names" onclick="fnGetId()">

[jsudds] This isn't a "working" example of the problem. The script here, which was copied from the topic above, does not generate an error message. I tried to implement the behavior you describe, by using the script name and a global object, but both IE6 and IE7 run it flawlessly.

<script type="text/javascript">
function fnGetId()
{
   var oDiv1 = document.getElementById("fnGetId");
alert(oDiv1.innerHTML);

var oDiv2 = document.getElementById("window");
alert(oDiv2.innerHTML);
}
</script>
<div id="fnGetId">Div #1</div>
<div id="window">Div #2</div>
<input type="button" value="Get Names" onclick="fnGetId()"/>

Can you provide a repro?

[sglass] There's no doubt this exists. We've been dealing with this issue for the past two days. Turns out we were using this shared library called mootools. Within mootools they had defined a function called getElementById(). Once I renamed this method in mootools, my problem dissappeared. This seems to be plaguing a lot of IE users out there. Hopefully they'll find this and get past it.

[arnoschaefer]

I can reproduce the "Object doesn't support this property or method" error in IE8 when omitting the "var" keyword, thus declaring the variable implicitly in the global context:

<script type="text/javascript">
function doit () {
a = document.getElementById ("a");
alert (a);
}
</script>
</head>
<body onload="doit ();">
<h1 id="a">foo</h1>
</body>
It appears that IE implicitly declares named DOM nodes as "constants" in the global scope, so I can access "a" directly without using "getElementById" first (try commenting out the "getElementById" line). Every attempt to overwrite these generates the abovementioned error. The error can of course be fixed by using the "var" keyword, thus putting the variable "a" in the local scope. Does anyone know more about this behavior? Is this documented elsewhere?



Scott Trenda
bug with self-terminating tags

Do the following:

<div id="a"></div>
<div id="b"></div>
<script type="text/javascript">
document.getElementById("a").innerHTML = "test";
document.getElementById("b").innerHTML = "test";
</script>

and the following:

<div id="a" />
<div id="b" />
<script type="text/javascript">
document.getElementById("a").innerHTML = "test";
document.getElementById("b").innerHTML = "test";
</script>

They do not work exactly the same way, even though they should, since <tag></tag> is the same as <tag />.


[Scott Trenda]

<tag></tag> is the same as <tag /> in XML, but not in HTML. You need to explicitly open and close the tag in order for the HTML parser to correctly interpret the structure.


Zoroxeus
Bug with getElementById

There seems to be a problem with IE6 & 7 and the getElementById function

When looking for an Id in a DIV everything works perfectly fine, however if the DIV is inside a form, the DIV is not found...

Ohter browsers such as Opera, Safari and Firefox work fine...

Is there any workaround ?

Tags : contentbug

Mr. Raymond Kenneth Petry
caution - obscure error

N.B. #1.

There exists a strange data type, call it, hole,
for which document.getElementById(hole)
generates an error, instead of a null object...

This data type, hole, is the blank value
of ... srcElement.parentElement.id ...
where ... there is no id, in an A-element ...

hole == blank,
hole != null,

It crashes getElementById() and cancels its JScript.

(I'm yet tracking it down... it's running deep.... Ray.)

N.B. #2.

By name, does not work in MSIE-6,7 ... And, returns differently:

A-element returns "" (blank);
P-element returns "null";
Q-element returns "null";
DIV, SPAN, BODY,,,, etc. return "null".

This latter is possibly documentation confusion, as NAME does not show in Parameters here.

Tags :

Page view tracker