EN
JavaScript - get html of whole webpage
15
points
In JavaScript, it is possible to get the HTML code of all web pages in the following ways.
1. document.documentElement
property example
// ONLINE-RUNNER:browser;
<html>
<body>
<div>Web site code here ...</div>
<script>
var root = document.documentElement; // root element handle for current document
var html = root.outerHTML; // html of whole web site
console.log(html);
</script>
</body>
</html>
2. head
or body
parentNode
property example
// ONLINE-RUNNER:browser;
<html>
<body>
<div>Web site code here ...</div>
<script>
function getRoot(document) {
var element = document.head || document.body;
while (true) {
var parent = element.parentNode;
if (parent == null || parent == document) {
return element;
}
element = parent;
}
}
var root = getRoot(document); // root element handle for current document
var html = root.outerHTML; // html of whole web site
console.log(html);
</script>
</body>
</html>
3. document.querySelector
method example
// ONLINE-RUNNER:browser;
<html>
<body>
<div>Web site code here ...</div>
<script>
var root = document.querySelector('html'); // element handle for current document
var html = root.outerHTML; // html of whole web site
console.log(html);
</script>
</body>
</html>
Note: using this approach you need to be sure that
html
tag is unique in your document.
4. jQuery prop
method example
// ONLINE-RUNNER:browser;
<html>
<head>
<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
</head>
<body>
<div>Web site code here ...</div>
<script>
$(document).ready(function() {
var root = $('html');
var html = root.prop('outerHTML');
console.log(html);
});
</script>
</body>
</html>
Note: using this approach you need to be sure that
html
tag is unique in your document.