How to Get the Entire HTML Document as a String Using JavaScript?
We will explore how to retrieve the entire HTML document as a string using JavaScript. This can be useful when you want to inspect or manipulate the entire structure of a webpage.
Methods to Get the Entire HTML Document as a String
There are two primary methods for extracting the HTML content of a page as a string:
Table of Content
Method 1: Using getElementsByTagName()
The getElementsByTagName() method is used to select all elements in the document with a specific tag name. It returns a NodeList object, which is like an array of nodes (HTML elements), and each node can be accessed using an index starting from 0.
Syntax:
document.getElementsByTagName(tagname);
Example: This example gets the whole document by first selecting the elements with the tag name 'HTML' and selecting the first element by indexing using document.getElementsByTagName('html')[0].innerHTML.
<!DOCTYPE html>
<html>
<head>
<title>
How to get the entire HTML document as a string
in JavaScript ?
</title>
</head>
<body style="text-align: center" id="body">
<h1 style="color: green">GeeksforGeeks</h1>
<h3>
JavaScript | Get the entire document HTML as a
string.
</h3>
<p id="GFG_UP" style="font-size: 15px; font-weight: bold"></p>
<button onclick="GFG_Fun(); ">click here</button>
<script>
let up = document.getElementById("GFG_UP");
up.innerHTML =
"Click on the button to convert whole document to string";
function GFG_Fun() {
let string =
document.getElementsByTagName("html")[0]
.innerHTML;
alert(string);
}
</script>
</body>
</html>
Output:

Method 2: Using the innerHTML Property
Another way to get the entire HTML document is by using the innerHTML property. This property is used to get or set the HTML content inside an element. It can be applied to any element in the DOM (Document Object Model).
Syntax:
HTMLElementObject.innerHTML
Example: This example gets the whole document as a string using document.documentElement.innerHTML.
<!DOCTYPE html>
<html>
<head>
<title>
How to get the entire HTML document as a string
in JavaScript ?
</title>
</head>
<body style="text-align: center" id="body">
<h1 style="color: green">GeeksforGeeks</h1>
<h3>
JavaScript | Get the entire document HTML as a
string.
</h3>
<p id="GFG_UP" style="font-size: 15px; font-weight: bold"></p>
<button onclick="GFG_Fun(); ">click here</button>
<script>
let up = document.getElementById("GFG_UP");
up.innerHTML =
"Click on the button to convert whole document to string";
function GFG_Fun() {
let string =
document.documentElement.innerHTML;
alert(string);
}
</script>
</body>
</html>
Output:
