【问题标题】:How do I get the entire page's HTML with jQuery?如何使用 jQuery 获取整个页面的 HTML?
【发布时间】:2010-11-02 05:37:45
【问题描述】:

我使用了$(document).html(),但是这引发了错误...有没有办法得到所有东西?

【问题讨论】:

    标签: jquery html dom


    【解决方案1】:

    编辑:使用XMLSerializer()

    别忘了<html> 标签也可以有属性。如果您想要整个文档,这应该可以工作。

     $('html')[0].outerHTML
    

    没有 jQuery 也很简单。

    document.documentElement.outerHTML
    

    如果你也想include the doctype,那就有点牵扯了。

    var getDocTypeAsString = function () { 
        var node = document.doctype;
        return node ? "<!DOCTYPE "
             + node.name
             + (node.publicId ? ' PUBLIC "' + node.publicId + '"' : '')
             + (!node.publicId && node.systemId ? ' SYSTEM' : '') 
             + (node.systemId ? ' "' + node.systemId + '"' : '')
             + '>\n' : '';
    };
    
    getDocTypeAsString() + document.documentElement.outerHTML   
    

    【讨论】:

      【解决方案2】:

      你可以试试:

      $("html").html();
      

      如果您还想捕获 html 标签,您可以像这样将它们连接到 html:

      function getPageHTML() {
        return "<html>" + $("html").html() + "</html>";
      }
      

      【讨论】:

      • 获取文档类型怎么样?
      • @Sebastian 不确定是否可以,请参阅this answer
      • 这可以工作,但如果你用整个其他页面替换一个页面,你最终会拥有多个 html 标记。
      【解决方案3】:

      用途:

      document.body.innerHTML
      

      【讨论】:

      • 如果您想要整个文档 html,您应该使用:window.document.innerHTML
      • @simo: document 在我仍在使用的任何浏览器中都没有 innerHTML 属性。
      【解决方案4】:

      $("html").html() 将获取除最外层 html 标记之外的所有内容。

      【讨论】:

      • 这个答案比公认的答案还有什么?
      【解决方案5】:

      无需依赖 jQuery。最好和最简单的方法是使用

      new XMLSerializer().serializeToString(document)
      

      它将始终为您提供整个页面的内容包括 DOCTYPE标签,并且在所有现代浏览器中都支持:https://caniuse.com/#feat=xml-serializer

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-10-07
        • 2012-03-21
        • 1970-01-01
        相关资源
        最近更新 更多