Languages
[Edit]
EN

JavaScript - get html of whole webpage

15 points
Created by:
p_agon
589

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.

Alternative titles

  1. JavaScript - how to get html of all webpage?
  2. JavaScript - how to get html of all web page?
  3. JavaScript - how to get html of whole web page?
  4. JavaScript - how to get outer html of root element?
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join