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

10 comments

  1. 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. 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. 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. It’s been added to recent Safari 2.0 seeds.

  5. Yeah, I saw that when browsing their source code

  6. Bosco

    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

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

  8. 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?

  9. I keep getting this phrase ‘DOMparser’ is unefined when I try loggin into face

  10. Rajib

    thanks

Comments are closed.