views:

83

answers:

1

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 xmlfile 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, where as alert(resultNode) returns null everytime.

+2  A: 

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
Thanks Tim. Exactly what I was looking for.
Sharad