html-domparser.js 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. /**
  2. * DOMParser HTML extension
  3. * 2012-09-04
  4. *
  5. * By Eli Grey, http://eligrey.com
  6. * Public domain.
  7. * NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.
  8. *
  9. * SPDX-FileCopyrightText: 2012 Eli Grey, http://eligrey.com
  10. * SPDX-License-Identifier: CC0-1.0
  11. */
  12. /*! @source https://gist.github.com/1129031 */
  13. /*global document, DOMParser*/
  14. (function(DOMParser) {
  15. "use strict";
  16. var
  17. DOMParser_proto = DOMParser.prototype
  18. , real_parseFromString = DOMParser_proto.parseFromString
  19. ;
  20. // Firefox/Opera/IE throw errors on unsupported types
  21. try {
  22. // WebKit returns null on unsupported types
  23. if ((new DOMParser).parseFromString("", "text/html")) {
  24. // text/html parsing is natively supported
  25. return;
  26. }
  27. } catch (ex) {}
  28. DOMParser_proto.parseFromString = function(markup, type) {
  29. if (/^\s*text\/html\s*(?:;|$)/i.test(type)) {
  30. var
  31. doc = document.implementation.createHTMLDocument("")
  32. ;
  33. if (markup.toLowerCase().indexOf('<!doctype') > -1) {
  34. doc.documentElement.innerHTML = markup;
  35. }
  36. else {
  37. doc.body.innerHTML = markup;
  38. }
  39. return doc;
  40. } else {
  41. return real_parseFromString.apply(this, arguments);
  42. }
  43. };
  44. }(DOMParser));