DOMParser for IE and Safari

A few days ago Dave over at the WebGraphics blog posted about how to parse a string into a DOM tree for Safari.

I commented “How about implementing the DOMParser object in js?” and before I knew it I did it myself and adding IE compatibility on the way:

if (typeof DOMParser == "undefined") {
   DOMParser = function () {}

   DOMParser.prototype.parseFromString = function (str, contentType) {
      if (typeof ActiveXObject != "undefined") {
         var d = new ActiveXObject("MSXML.DomDocument");
         d.loadXML(str);
         return d;
      } else if (typeof XMLHttpRequest != "undefined") {
         var req = new XMLHttpRequest;
         req.open("GET", "data:" + (contentType || "application/xml") +
                         ";charset=utf-8," + encodeURIComponent(str), false);
         if (req.overrideMimeType) {
            req.overrideMimeType(contentType);
         }
         req.send(null);
         return req.responseXML;
      }
   }
}

Both Opera and Mozilla already have this object

8 Responses to “DOMParser for IE and Safari”

  1. Matt Seeley Says:

    Very useful. Only recommendation is to change the PROGID value for IE. Seems “Msxml2.DOMDocument” is the best bet as it will always get the most recent version (

  2. Matt Seeley Says:

    up until v4.0.

    Burst has some nice documenation about this

    http://burstproject.org/build/apidoc/html/classburst_1_1xml_1_1XmlDoc.html

    sorry about the double post.

  3. Erik Arvidsson Says:

    Thanks for the link. The only reason I can see for not using IXMLDOMDocument is that one might want to use XPath and then IXMLDOMDocument2 must be used.

  4. Randy Reddig Says:

    It’s been added to recent Safari 2.0 seeds.

  5. Erik Arvidsson Says:

    Yeah, I saw that when browsing their source code

  6. Bosco Says:

    I used the code above but I could only get error code: No such interface supported… but when I tried to print out the nodes the structure of the returned object seems to be well constructed.

    Please advise

  7. jiajia Says:

    Would you mind tell me which editor you are using for javascript file?

  8. n[ate]vw Says:

    Shouldn’t the line:

    if (req.overrideMimeType) { req.overrideMimeType(contentType); }

    be instead:

    if (contentType && req.overrideMimeType) { req.overrideMimeType(contentType); }

    as the lines above treat contentType as an optional argument?

Leave a Reply