XMLDocument.getElementById()

Getting element with specified ID (eg. id="id1") from XML file received via xmlHttpRequest is really hard! Let’s take the following JavaScript code:

1
2
3
4
5
6
7
8
9
10
11
12
var ajax = new XMLHttpRequest();
ajax.open('GET', 'test.xml');
ajax.onreadystatechange = function() {
if(ajax.readyState == 4 && ajax.status == 200) {
var doc = ajax.responseXML;
doc.getElementById('id1').appendChild(
doc.createTextNode('abc')
);
// anything else...
}
};
ajax.send();

and test.xml:

1
2
3
4
<xml>
<thiselement id="id1" />
<thiselement id="id2" />
</xml>

You know what would happen? Script will fail (in Firefox and Opera; Chrome will do fine) in this line:

1
doc.getElementById('id1').appendChild()

It’s obvious that you cannot convert doc.getElementById('id1') to object, right? If not - go ahead.

Your browser does not know (or does not want to know), that id="" is really a unique identifier. Everything will start to work when, at the beginning of an XML file, we put:

1
<!DOCTYPE xml [ <!ATTLIST tenelement id ID #IMPLIED> ]>

Until… we would try to send this document to the server:

1
2
3
4
var ajax2 = new XMLHttpRequest();
ajax2.open('POST', 'save.php');
ajax2.onreadystatechange = function() {};
ajax2.send(ajax.responseXML);

Browser will send the DOCTYPE, but without the most important thing ([ <!ATTLIST tenelement id ID #IMPLIED> ]). To make it work, I had to modify the received file in save.php by adding a missing part of a DOCTYPE. Someone knows a better solution?