XML: IDs and the DOM

In XML, IDs are treated differently from HTML. Since XML has no predefined DTD, an ID attribute has no special meaning for a user-agent that tries to access an element through the DOM. Further, since browsers (the most used UAs on the web) don't use DTDs when they access documents, even if you specify and ID attribute in your custom DTD (by using ATTLIST) the default browser's behavior won't change. The only way you have to mimic the basic functionalities of HTML DOM is to add the XHTML namespace to your target element or to its nearest ancestor.

For example, given the following XML document:

<?xml version="1.0" encoding="utf-8"?>

<para id="test">Test</para>


If you try to access the element with ID test, you get null:

// null

This happens because in the XML DOM there's no predefined attribute associated with that element. Instead, you have to access the aforementioned element using a more general approach:

alert(document.querySelector('root para:first-child'));
// [object Element]

As said earlier, a quick-and-dirty way to fix this problem is to set the XHTML namespace on a nearest ancestor, for example the root element:

<?xml version="1.0" encoding="utf-8"?>
<root xmlns="http://www.w3.org/1999/xhtml">

<para id="test">Test</para>


Now DOM methods such as getElementById() will work as expected.

Leave a Reply

Note: Only a member of this blog may post a comment.