在JS中是否有一种方法可以在HTML标签中获取整个HTML,作为字符串?
document.documentElement.??
在JS中是否有一种方法可以在HTML标签中获取整个HTML,作为字符串?
document.documentElement.??
当前回答
我只需要doctype html,应该可以在IE11, Edge和Chrome中正常工作。我使用下面的代码,它工作得很好。
function downloadPage(element, event) {
var isChrome = /Chrome/.test(navigator.userAgent) && /Google Inc/.test(navigator.vendor);
if ((navigator.userAgent.indexOf("MSIE") != -1) || (!!document.documentMode == true)) {
document.execCommand('SaveAs', '1', 'page.html');
event.preventDefault();
} else {
if(isChrome) {
element.setAttribute('href','data:text/html;charset=UTF-8,'+encodeURIComponent('<!doctype html>' + document.documentElement.outerHTML));
}
element.setAttribute('download', 'page.html');
}
}
在你的锚标签中像这样使用。
<a href="#" onclick="downloadPage(this,event);" download>Download entire page.</a>
例子
function downloadPage(element, event) { var isChrome = /Chrome/.test(navigator.userAgent) && /Google Inc/.test(navigator.vendor); if ((navigator.userAgent.indexOf("MSIE") != -1) || (!!document.documentMode == true)) { document.execCommand('SaveAs', '1', 'page.html'); event.preventDefault(); } else { if(isChrome) { element.setAttribute('href','data:text/html;charset=UTF-8,'+encodeURIComponent('<!doctype html>' + document.documentElement.outerHTML)); } element.setAttribute('download', 'page.html'); } } I just need doctype html and should work fine in IE11, Edge and Chrome. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. <p> <a href="#" onclick="downloadPage(this,event);" download><h2>Download entire page.</h2></a></p> <p>Some image here</p> <p><img src="https://placeimg.com/250/150/animals"/></p>
其他回答
document.documentElement.innerHTML
document.documentElement.outerHTML
您必须遍历文档childNodes并获得outerHTML内容。
在VBA中是这样的
For Each e In document.ChildNodes
Put ff, , e.outerHTML & vbCrLf
Next e
使用这个,允许你获得网页的所有元素,包括< !DOCTYPE >节点(如果它存在的话)
MS在一段时间前添加了outerHTML和innerHTML属性。
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解析和序列化规范中。
查看quirksmode浏览器兼容性,了解适合您的浏览器。都支持innerHTML。
var markup = document.documentElement.innerHTML;
alert(markup);
我总是用
document.getElementsByTagName('html')[0].innerHTML
可能不是正确的方式,但当我看到它时,我能理解它。