html-domparser.js 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  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. /*! @source https://gist.github.com/1129031 */
  10. /*global document, DOMParser*/
  11. (function(DOMParser) {
  12. "use strict";
  13. var
  14. DOMParser_proto = DOMParser.prototype
  15. , real_parseFromString = DOMParser_proto.parseFromString
  16. ;
  17. // Firefox/Opera/IE throw errors on unsupported types
  18. try {
  19. // WebKit returns null on unsupported types
  20. if ((new DOMParser).parseFromString("", "text/html")) {
  21. // text/html parsing is natively supported
  22. return;
  23. }
  24. } catch (ex) {}
  25. DOMParser_proto.parseFromString = function(markup, type) {
  26. if (/^\s*text\/html\s*(?:;|$)/i.test(type)) {
  27. var
  28. doc = document.implementation.createHTMLDocument("")
  29. ;
  30. if (markup.toLowerCase().indexOf('<!doctype') > -1) {
  31. doc.documentElement.innerHTML = markup;
  32. }
  33. else {
  34. doc.body.innerHTML = markup;
  35. }
  36. return doc;
  37. } else {
  38. return real_parseFromString.apply(this, arguments);
  39. }
  40. };
  41. }(DOMParser));