4

Is document.getElementById method supported on DOM parsed from XML strings using the DOMParser method in Mozilla? I am making a Mozilla extension that reads an XML file and uses DOM Parser to convert the XML into a DOM element and tries getting elements by Id. The method getElementsByTagName works but not getElementById. It always returns null.

function (xmlString) {
    var parser = new DOMParser();
    var doc = parser.parseFromString(xmlString, "text/xml"); 
    var aNodes = doc.getElementsByTagName("nodeTag");
    for(var i=0; i<aNodes.length; ++i) {
        var id = aNodes[i].getAttribute('id');
        var resultNode = doc.getElementById(id);
        alert(id);
        alert(resultNode);
    }
}

I tried the above code. alert(id) returns the proper id, whereas alert(resultNode) returns null every time.

Sami Ahmed Siddiqui
  • 2,328
  • 1
  • 16
  • 29
Sharad
  • 963
  • 11
  • 24

2 Answers2

8

No, document.getElementById doesn't generally work on arbitrary XML documents.

In recent browsers (e.g. Firefox 3.5 and later), you can use document.querySelector instead:

var resultNode = doc.querySelector("[id=" + id + "]");
Tim Down
  • 318,141
  • 75
  • 454
  • 536
  • Yes, but of course that returns attributes whose name is "id", not attributes whose type is ID. – Michael Kay Sep 08 '11 at 14:38
  • @Michael: Indeed, but I suspect that may be good enough for the OP. Besides, does `DOMParser` read DTDs? – Tim Down Sep 08 '11 at 15:32
  • 2
    Extracted from w3 DOM-Level-2-Core documentation, "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." so this is why it don't run as expected. – PhoneixS Jan 11 '13 at 10:40
3

If you would like a solution that actually makes the getElementById() method usable (which you should, It is much much faster, and more versatile) and you have access to the DTD add the following line to it:

<!ATTLIST client id ID #IMPLIED >

If you aren't using a DTD yet, just add this to the xml document directly after the <?xml version= \"1.0\"?> statement:

<!DOCTYPE clients [ 
   <!ATTLIST client id ID #IMPLIED > 
]>

In this example "clients" is the root of my xml file, and "client" is the element i would like to attach id's to. You can add multiple "ATTLIST" statements for other elements you would like to add id's to other types of elements.

I tested this in safari, chrome, and firefox. works perfectly.

VoltzRoad
  • 475
  • 2
  • 6
  • 11