繁体   English   中英

如何使用JavaScript创建Document对象

[英]How to create Document objects with JavaScript

基本上这就是问题,如何在javascript中动态地从HTML字符串构造一个Document对象?

规范中定义了两种方法,DOM Core Level 2中的createDocument和HTML5中的createHTMLDocument 前者创建XML文档(包括XHTML),后者创建HTML文档。 两者都作为函数驻留在DOMImplementation接口上。

var impl    = document.implementation,
    xmlDoc  = impl.createDocument(namespaceURI, qualifiedNameStr, documentType),
    htmlDoc = impl.createHTMLDocument(title);

实际上,这些方法相当年轻,仅在最近的浏览器版本中实现。 根据http://quirksmode.orgMDN ,以下浏览器支持createHTMLDocument

  • Chrome 4
  • 歌剧10
  • Firefox 4
  • Internet Explorer 9
  • Safari 4

有趣的是,您可以(使用ActiveXObject )在较旧版本的Internet Explorer中创建HTML文档:

var htmlDoc = new ActiveXObject("htmlfile");

生成的对象将是一个新文档,可以像处理任何其他文档一样进行操作。

假设您正尝试从标记字符串和内容类型创建完全解析的Document对象,您也碰巧知道(可能是因为您从xmlhttprequest获取了html,因此在其Content-Type http中获得了内容Content-Type标题;可能通常是text/html ) - 它应该很简单:

var doc = (new DOMParser).parseFromString(markup, mime_type);

在一个理想的未来世界中,浏览器DOMParser实现与文档渲染一样强大和有能力 - 也许这是未来HTML6标准工作的良好管道梦想要求。 但事实证明,当前的浏览器并没有这样做。

你可能有一个更简单(但仍然很混乱)的问题,就是你需要一个html字符串来获得一个完全解析的Document对象。 这是另一个如何做到这一点,它也应该在所有浏览器中工作 - 首先你创建一个HTML Document对象:

var doc = document.implementation.createHTMLDocument('');

然后用你的html片段填充它

doc.open();
doc.write(html);
doc.close();

现在你应该在doc中有一个完全解析的DOM,你可以运行alert(doc.title) on,使用doc.querySelectorAll('p')等css选择器切片,或者使用doc.evaluate ditto XPath。

这实际上适用于现代WebKit浏览器,如Chrome和Safari(我刚刚分别在Chrome 22和Safari 6中测试过) - 这是一个采用当前页面源代码的示例,在新的文档变量src重新创建它,读出它的标题,用相同源代码的html引用版本覆盖它并在iframe中显示结果: http//codepen.io/johan/full/KLIeE

遗憾的是,我认为其他任何当代浏览器都没有相当可靠的实现。

随着DOMparser的发展,2014年的更新答案。 这适用于我能找到的所有当前浏览器,并且应该在早期版本的IE中使用ecManaut的document.implementation.createHTMLDocument('')方法。

从本质上讲,IE,Opera,Firefox都可以解析为“text / html”。 Safari解析为“text / xml”。

但要注意不容忍的XML解析。 Safari解析将在不间断的空格和其他带有&符号的HTML字符(法语/德语口音)中分解。 下面的代码不是单独处理每个字符,而是用无意义的字符串“j!J!”替换所有的&符号。 随后在浏览器中显示结果时,此字符串可以重新呈现为&符号(我发现,比在“错误”XML解析中尝试处理&符号更简单)。

function parseHTML(sText) {
try {

    console.log("Domparser: " + typeof window.DOMParser);

    if (typeof window.DOMParser !=null) {
        // modern IE, Firefox, Opera  parse text/html
        var parser = new DOMParser();
        var doc = parser.parseFromString(sText, "text/html");
        if (doc != null) {
            console.log("parsed as HTML");
            return doc

        }
        else {

            //replace ampersands with harmless character string to avoid XML parsing issues
            sText = sText.replace(/&/gi, "j!J!");
            //safari parses as text/xml
            var doc = parser.parseFromString(sText, "text/xml");
            console.log("parsed as XML");
            return doc;
        }

    } 
    else  {
        // older IE 
        doc= document.implementation.createHTMLDocument('');
        doc.write(sText);           
        doc.close;
        return doc; 
    }
} catch (err) {
    alert("Error parsing html:\n" + err.message);
}
}

根据规范( doc ),可以使用DOMImplementationcreateHTMLDocument方法,可通过document.implementation访问,如下所示:

var doc = document.implementation.createHTMLDocument('My title');  
var body = document.createElementNS('http://www.w3.org/1999/xhtml', 'body'); 
doc.documentElement.appendChild(body);
// and so on

以下适用于大多数常见浏览器,但不是一些。 应该是多么简单(但不是):

// Fails if UA doesn't support parseFromString for text/html (e.g. IE)
function htmlToDoc(markup) {
  var parser = new DOMParser();
  return parser.parseFromString(markup, "text/html");
}

var htmlString = "<title>foo bar</title><div>a div</div>";
alert(htmlToDoc(htmlString).title);

为了解释用户代理变幻莫测,以下可能更好(请注意归属地):

/*
 * DOMParser HTML extension
 * 2012-02-02
 *
 * By Eli Grey, http://eligrey.com
 * Public domain.
 * NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.
 *
 * Modified to work with IE 9 by RobG
 * 2012-08-29
 *
 * Notes:
 *
 *  1. Supplied markup should be avalid HTML document with or without HTML tags and
 *     no DOCTYPE (DOCTYPE support can be added, I just didn't do it)
 *
 *  2. Host method used where host supports text/html
 */

/*! @source https://gist.github.com/1129031 */
/*! @source https://developer.mozilla.org/en-US/docs/DOM/DOMParser */

/*global document, DOMParser*/

(function(DOMParser) {
    "use strict";

    var DOMParser_proto;
    var real_parseFromString;
    var textHTML;         // Flag for text/html support
    var textXML;          // Flag for text/xml support
    var htmlElInnerHTML;  // Flag for support for setting html element's innerHTML

    // Stop here if DOMParser not defined
    if (!DOMParser) return;

    // Firefox, Opera and IE throw errors on unsupported types
    try {
        // WebKit returns null on unsupported types
        textHTML = !!(new DOMParser).parseFromString('', 'text/html');

    } catch (er) {
      textHTML = false;
    }

    // If text/html supported, don't need to do anything.
    if (textHTML) return;

    // Next try setting innerHTML of a created document
    // IE 9 and lower will throw an error (can't set innerHTML of its HTML element)
    try {
      var doc = document.implementation.createHTMLDocument('');
      doc.documentElement.innerHTML = '<title></title><div></div>';
      htmlElInnerHTML = true;

    } catch (er) {
      htmlElInnerHTML = false;
    }

    // If if that failed, try text/xml
    if (!htmlElInnerHTML) {

        try {
            textXML = !!(new DOMParser).parseFromString('', 'text/xml');

        } catch (er) {
            textHTML = false;
        }
    }

    // Mess with DOMParser.prototype (less than optimal...) if one of the above worked
    // Assume can write to the prototype, if not, make this a stand alone function
    if (DOMParser.prototype && (htmlElInnerHTML || textXML)) { 
        DOMParser_proto = DOMParser.prototype;
        real_parseFromString = DOMParser_proto.parseFromString;

        DOMParser_proto.parseFromString = function (markup, type) {

            // Only do this if type is text/html
            if (/^\s*text\/html\s*(?:;|$)/i.test(type)) {
                var doc, doc_el, first_el;

                // Use innerHTML if supported
                if (htmlElInnerHTML) {
                    doc = document.implementation.createHTMLDocument("");
                    doc_el = doc.documentElement;
                    doc_el.innerHTML = markup;
                    first_el = doc_el.firstElementChild;

                // Otherwise use XML method
                } else if (textXML) {

                    // Make sure markup is wrapped in HTML tags
                    // Should probably allow for a DOCTYPE
                    if (!(/^<html.*html>$/i.test(markup))) {
                        markup = '<html>' + markup + '<\/html>'; 
                    }
                    doc = (new DOMParser).parseFromString(markup, 'text/xml');
                    doc_el = doc.documentElement;
                    first_el = doc_el.firstElementChild;
                }

                // RG: I don't understand the point of this, I'll leave it here though 
                //     In IE, doc_el is the HTML element and first_el is the HEAD.
                //
                // Is this an entire document or a fragment?
                if (doc_el.childElementCount == 1 && first_el.localName.toLowerCase() == 'html') {
                    doc.replaceChild(first_el, doc_el);
                }

                return doc;

            // If not text/html, send as-is to host method
            } else {
                return real_parseFromString.apply(this, arguments);
            }
        };
    }
}(DOMParser));

// Now some test code
var htmlString = '<html><head><title>foo bar</title></head><body><div>a div</div></body></html>';
var dp = new DOMParser();
var doc = dp.parseFromString(htmlString, 'text/html');

// Treat as an XML document and only use DOM Core methods
alert(doc.documentElement.getElementsByTagName('title')[0].childNodes[0].data);

不要被代码量拖延,有很多评论,它可以缩短很多但是变得不那么可读。

哦,如果标记是有效的XML,生活就会简单得多:

var stringToXMLDoc = (function(global) {

  // W3C DOMParser support
  if (global.DOMParser) {
    return function (text) {
      var parser = new global.DOMParser();
      return parser.parseFromString(text,"application/xml");
    }

  // MS ActiveXObject support
  } else {
    return function (text) {
      var xmlDoc;

      // Can't assume support and can't test, so try..catch
      try {
        xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
        xmlDoc.async="false";
        xmlDoc.loadXML(text);
      } catch (e){}
      return xmlDoc;
    }
  }
}(this));


var doc = stringToXMLDoc('<books><book title="foo"/><book title="bar"/><book title="baz"/></books>');
alert(
  doc.getElementsByTagName('book')[2].getAttribute('title')
);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM