How do I get the entire page's HTML with jQuery?

后端 未结 5 659
有刺的猬
有刺的猬 2020-11-27 04:45

I used $(document).html(), but that threw an error... is there a way to get everything?

相关标签:
5条回答
  • 2020-11-27 05:00

    You could try:

    $("html").html();
    

    If you want to also capture the html tags you could concatenate them to the html like this:

    function getPageHTML() {
      return "<html>" + $("html").html() + "</html>";
    }
    
    0 讨论(0)
  • 2020-11-27 05:01

    No need to lean on jQuery. The best and simplest approach is to use

    new XMLSerializer().serializeToString(document)
    

    which will always give you the contents of the entire page including DOCTYPE tag, and it is supported in all modern browsers: https://caniuse.com/#feat=xml-serializer

    0 讨论(0)
  • 2020-11-27 05:04

    Use:

    document.body.innerHTML
    
    0 讨论(0)
  • 2020-11-27 05:05

    $("html").html() would get everything but the outer most html tags.

    0 讨论(0)
  • 2020-11-27 05:09

    Don't forget the <html> tag can have attributes too. If you want the whole document this should work.

     $('html')[0].outerHTML
    

    It's also trivial without jQuery.

    document.documentElement.outerHTML
    

    If you also want to include the doctype, it's a little more involved.

    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   
    
    0 讨论(0)
提交回复
热议问题