在JS中是否有一种方法可以在HTML标签中获取整个HTML,作为字符串?
document.documentElement.??
在JS中是否有一种方法可以在HTML标签中获取整个HTML,作为字符串?
document.documentElement.??
当前回答
我总是用
document.getElementsByTagName('html')[0].innerHTML
可能不是正确的方式,但当我看到它时,我能理解它。
其他回答
正确的做法其实是:
webBrowser1。DocumentText
如果你想获取DOCTYPE之外的所有内容,这将有效:
document.getElementsByTagName('html')[0].outerHTML;
如果你想要doctype也可以这样:
new XMLSerializer().serializeToString(document.doctype) + document.getElementsByTagName('html')[0].outerHTML;
我总是用
document.getElementsByTagName('html')[0].innerHTML
可能不是正确的方式,但当我看到它时,我能理解它。
还可以获取<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.getElementsByTagName('html')[0].innerHTML
你不会得到Doctype或html标签,但其他的一切…