2012-02-29 53 views
4
解析HTML字符串

這裏的來的片段:麻煩試圖用的DOMParser

html = "<!doctype html>"; 
html += "<html>"; 
html += "<head><title>test</title></head>"; 
html += "<body><p>test</p></body>"; 
html += "</html>"; 

parser = new DOMParser(); 

dom = parser.parseFromString (html, "text/html"); 

這裏的來試圖執行這些線路時出現錯誤:

錯誤:組件返回故障代碼:0x80004001(NS_ERROR_NOT_IMPLEMENTED )[nsIDOMParser.parseFromString]

我試圖找出發生了什麼,但代碼似乎是正確的,我在網上搜索,我來到這裏沒有線索。

你以前遇到過這個故障嗎?如果是的話,隱藏的bug在哪裏?

+0

請檢查該http://stackoverflow.com/questions/9250545/javascript-domparser-access-innerhtml - 和 - 其他屬性和這個http://stackoverflow.com/questions/888875/how-to-parse-html-from-javascript-in-firefox – arunes 2012-02-29 13:56:57

+0

@arunes我用'text/html'這就是爲什麼我沒有得到錯誤 – user544262772 2012-02-29 14:09:04

回答

13

您應該使用在JavaScript DOMParser access innerHTML and other properties

我創建小提琴描述的DOMParser功能爲您http://jsfiddle.net/CSAnZ/

/* 
* DOMParser HTML extension 
* 2012-02-02 
* 
* 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("") 
       , doc_elt = doc.documentElement 
       , first_elt; 

      doc_elt.innerHTML = markup; 
      first_elt = doc_elt.firstElementChild; 

      if (doc_elt.childElementCount === 1 
       && first_elt.localName.toLowerCase() === "html") { 
       doc.replaceChild(first_elt, doc_elt); 
      } 

      return doc; 
     } else { 
      return real_parseFromString.apply(this, arguments); 
     } 
    }; 
}(DOMParser)); 
+0

真棒男人:)我看到這個功能深入研究,但我真的很遠沒有想到我不要這樣做。謝謝 ! – user544262772 2012-02-29 14:34:16

+0

保存我的一週,謝謝! – Carlos 2012-09-07 06:52:01