subbu.org

Ajax and getElementById

with one comment

Ever wonder why the method getElementById returns null when applied to responseXML of XMLHttpRequest?

Thomas Rabaix discusses about this problem briefly in his Issues when developing AJAX Libraries. Here is a more detailed answer.

In the snippet below, the value of getElementById() would be null.

request.onreadystatechange = function()
{
if(request.readyState == 4) {
if(request.status == 200) {
var info = request.responseXML.getElementById("someid");
alert(info);
}
}
};

In XML, attribute with name id is not automatic. For an element to have an attribute named id, an attribute with name id and type ID must be defined in a schema or DTD underlying an XML document. For instance, XHTML defines such an attribute. The ID type is defined in XML 1.0 and further in XML Schema to be an attribute with a value which must be unique within a given document.

DOM Level 2 describes the behavior of getElementById().

Returns the Element whose ID is given by elementId. If no such element exists, returns null. Behavior is not defined if more than one element has this ID.

Note: 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. Implementations that do not know whether attributes are of type ID or not are expected to return null.

Further, xml:id Version 1.0 encourages schemas to declare attributes named xml:id with the type xs:ID.

The bottomline is that, unless an attribute of type ID is known to the DOM implementation, this method with return null.

For responseXML.getElementById() to return an element with the matching id value, XMLHttpRequest implementations must be aware of the underlying schema/DTD that defines an id attribute of type ID. Currently browsers are not schema/DTD aware for XMLHttpRequests, although they support well-known DTDs like HTML and XHTML for documents.

I was reminded that the solution is to use xml:id attribute in the XML so that getElementById can recognize ID type attributes - Apr 18, 2008
  • Digg
  • del.icio.us
  • Google

April 26th, 2006 at 9:52 pm

Tagged with , ,

RSS feed

1 Comment »

Comment by Richard Dunne at 2007-04-09 07:30:30

I tried accessing http.responseText using and responsehandler e.g.
var x=http.responseText;
and then getElementById().innerHTML, e.g.
var y=x.getElementById(’y').innerHTML;
but I get “undifined is null or not an object”.
Could you offer any tips/insights?

 
Name (required)
E-mail (required - never shown publicly)
URI
Your Comment (smaller size | larger size)
You may use <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> in your comment.

Trackback responses to this post