在JS中是否有一种方法可以在HTML标签中获取整个HTML,作为字符串?
document.documentElement.??
在JS中是否有一种方法可以在HTML标签中获取整个HTML,作为字符串?
document.documentElement.??
当前回答
使用document.documentElement。
这里回答了同样的问题: https://stackoverflow.com/a/7289396/2164160
其他回答
我使用outerHTML的元素(主要<html>容器),和XMLSerializer的任何其他包括<!DOCTYPE>, <html>容器外的随机注释,或者其他可能在那里的东西。空格似乎没有保留在<html>元素之外,所以我默认使用sep="\n"添加换行符。
函数get_document_html(sep="\n") { 让HTML = ""; let xml = new XMLSerializer(); for (let n of document.childNodes) { if (n.nodeType == Node.ELEMENT_NODE) html += n.outerHTML + sep; 其他的 html += xml.serializeToString(n) + sep; } 返回html; } console.log (get_document_html()。片(0,200));
我相信document.documentElement.outerHTML应该为您返回该值。
MDN表示,目前支持的浏览器包括Firefox 11、Chrome 0.2、Internet Explorer 4.0、Opera 7、Safari 1.3、Android、Firefox Mobile 11、IE Mobile、Opera Mobile、Safari Mobile等。outerHTML在DOM解析和序列化规范中。
outerHTML属性上的MSDN页面指出IE 5+支持它。Colin的回答链接到W3C quirksmode页面,该页面很好地比较了跨浏览器兼容性(也有其他DOM特性)。
还可以获取<html>…</html>,最重要的是<!DOCTYPE……>声明,你可以遍历文档。childNodes,将它们转换为字符串:
const html = [...document.childNodes]
.map(node => nodeToString(node))
.join('\n') // could use '' instead, but whitespace should not matter.
function nodeToString(node) {
switch (node.nodeType) {
case node.ELEMENT_NODE:
return node.outerHTML
case node.TEXT_NODE:
// Text nodes should probably never be encountered, but handling them anyway.
return node.textContent
case node.COMMENT_NODE:
return `<!--${node.textContent}-->`
case node.DOCUMENT_TYPE_NODE:
return doctypeToString(node)
default:
throw new TypeError(`Unexpected node type: ${node.nodeType}`)
}
}
我把这段代码作为document-outerhtml发布在npm上。
注意上面的代码依赖于doctypeToString函数;它的实现可以如下所示(下面的代码以doctype-to-string的形式发布在NPM上):
function doctypeToString(doctype) {
if (doctype === null) {
return ''
}
// Checking with instanceof DocumentType might be neater, but how to get a
// reference to DocumentType without assuming it to be available globally?
// To play nice with custom DOM implementations, we resort to duck-typing.
if (!doctype
|| doctype.nodeType !== doctype.DOCUMENT_TYPE_NODE
|| typeof doctype.name !== 'string'
|| typeof doctype.publicId !== 'string'
|| typeof doctype.systemId !== 'string'
) {
throw new TypeError('Expected a DocumentType')
}
const doctypeString = `<!DOCTYPE ${doctype.name}`
+ (doctype.publicId ? ` PUBLIC "${doctype.publicId}"` : '')
+ (doctype.systemId
? (doctype.publicId ? `` : ` SYSTEM`) + ` "${doctype.systemId}"`
: ``)
+ `>`
return doctypeString
}
document.documentElement.outerHTML
如果你想获取DOCTYPE之外的所有内容,这将有效:
document.getElementsByTagName('html')[0].outerHTML;
如果你想要doctype也可以这样:
new XMLSerializer().serializeToString(document.doctype) + document.getElementsByTagName('html')[0].outerHTML;