-1

I am trying to convert my HTML string to a DOM element but I am getting a script error: Invalid argument. My Internet Explorer version is 9. Please suggest any solution. Below is the code:

function open(htmlstring)
{
    var parser = new DOMParser();
    var doc = parser.parseFromString(htmlstring,"text/html");
}   
Code_99
  • 43
  • 1
  • 5
  • There is no such method `parserFromString`. `My internet explorer version is 9` If you're trying to do web development, consider using a modern browser instead, else many things may break for you. – CertainPerformance Aug 09 '18 at 05:59
  • look like typo it should be `parseFromString` – soorapadman Aug 09 '18 at 06:02
  • Look at the [Browser Compatibilty](https://developer.mozilla.org/en-US/docs/Web/API/DOMParser#Browser_compatibility) of the MDN article. You'll see that `text/html` option for `parseFromString` has been added in IE10 only. – Kaiido Aug 09 '18 at 07:42

1 Answers1

0

Edit: If you're getting an invalid argument, it might be that the argument you're giving is badly formatted HTML, for this case you can just wrap it around a try, catch, and evaluate for the case where htmlstring is badly formatted.

You can use a DOMParser shim or polyfill.

/*
 * DOMParser HTML extension
 * 2012-09-04
 * 
 * By Eli Grey, http://eligrey.com
 * Public domain.
 * NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.
 */

/*! @source https://gist.github.com/1129031 */
/*global document, DOMParser*/

(function(DOMParser) {
    "use strict";

    var
      DOMParser_proto = DOMParser.prototype
    , real_parseFromString = DOMParser_proto.parseFromString
    ;

    // Firefox/Opera/IE throw errors on unsupported types
    try {
        // WebKit returns null on unsupported types
        if ((new DOMParser).parseFromString("", "text/html")) {
            // text/html parsing is natively supported
            return;
        }
    } catch (ex) {}

    DOMParser_proto.parseFromString = function(markup, type) {
        if (/^\s*text\/html\s*(?:;|$)/i.test(type)) {
            var
              doc = document.implementation.createHTMLDocument("")
            ;
                if (markup.toLowerCase().indexOf('<!doctype') > -1) {
                    doc.documentElement.innerHTML = markup;
                }
                else {
                    doc.body.innerHTML = markup;
                }
            return doc;
        } else {
            return real_parseFromString.apply(this, arguments);
        }
    };
}(DOMParser));

from: https://gist.github.com/eligrey/1129031 or just look for polyfills on google for internet explorer 9. There is even a complete ES6.js polyfill, the reason it doesn't work in IE9, is because such implementation is just very old, so many modern things don't work there.

Rainb
  • 1,965
  • 11
  • 32