How to get the entire document HTML as a string in JavaScript?

JavascriptWeb DevelopmentFront End Technology

To get the entire document HTML as a string, use the concept of innerHTML, like −



Following is the code −

<!DOCTYPE html>
<html lang="en">
   <meta charset="UTF-8">
   <meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="//">
<script src=""></script>
<script src=""></script>
<h1> Hello World </h1>
<p>This is the javascript program..</p>
   var entireDocumentHTMLAsAString = document.documentElement.innerHTML;

To run the above program, save the file name anyName.html(index.html). Right click on the file and select the option “Open with live server” in VS Code editor.


This will produce the following output −

Following is the output on console −

Updated on 27-Oct-2020 09:50:04