DOMParser for IE and Safari 11

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

  • http://mattseeley.com Matt Seeley

    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 (

  • http://mattseeley.com Matt Seeley

    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.

  • http://erik.eae.net Erik Arvidsson

    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.

  • http://shaderlab.com Randy Reddig

    It’s been added to recent Safari 2.0 seeds.

  • http://erik.eae.net Erik Arvidsson

    Yeah, I saw that when browsing their source code

  • 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

  • jiajia

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

  • http://www.extinguishedscholar.com/wpglob/ n[ate]vw

    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?

  • Pingback: Parsing XML data with DOMParser « Perfection Labs Development Tips()

  • http://facebook. Dee

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

  • Rajib

    thanks