如何使用 jQuery 获取整个页面的 HTML?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/982717/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 10:20:04  来源:igfitidea点击:

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

jqueryhtmldom

提问by Justin Lee

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

我用过$(document).html(),但那抛出了一个错误......有没有办法得到一切?

回答by Patrick McElhaney

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

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

 $('html')[0].outerHTML

It's also trivial without jQuery.

没有 jQuery,这也很简单。

document.documentElement.outerHTML


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

如果您还想包含 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   

回答by Jimmie R. Houts

You could try:

你可以试试:

$("html").html();

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

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

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

回答by Diodeus - James MacFarlane

Use:

用:

document.body.innerHTML

回答by Max Schmeling

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

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

回答by FurloSK

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

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

new XMLSerializer().serializeToString(document)

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

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