Languages
[Edit]
EN

JavaScript - how to get html of whole webpage?

12 points
Created by:
JustMike
3515

In JavaScript it is possible to get HTML code of all web page in following ways.

1. document.documentElement property example

// ONLINE-RUNNER:browser;

<html>
<body>
  <pre id="output"></pre>
  <script>

    var output = document.getElementById('output');
    var root = document.documentElement; // root element handle for current document

    output.innerText = root.outerHTML;

  </script>
</body>
</html>

2. head or body parentNode property example

// ONLINE-RUNNER:browser;

<html>
<body>
  <pre id="output"></pre>
  <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 output = document.getElementById('output');
    var root = getRoot(document); // root element handle for current document

    output.innerText = root.outerHTML;

  </script>
</body>
</html>

3. document.querySelector method example

// ONLINE-RUNNER:browser;

<html>
<body>
  <pre id="output"></pre>
  <script>

    var output = document.getElementById('output');
    var root = document.querySelector('html'); // element handle for current document

    output.innerText = root.outerHTML;

  </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>
  <pre id="output"></pre>
  <script>

    $(document).ready(function() {
        var root = $('html');
      	var html = root.prop('outerHTML');
      
        var output = $('#output');
        output.text(html);
    });

  </script>
</body>
</html>

Note: using this approach you need to be sure that html tag is unique in your document.

Hey 👋
Would you like to know what we do?
  • Dirask is a friendly IT community for learners, professionals and hobbyists to share their knowledge and help each other in extraordinary easy way.
  • We welcome everyone,
    no matter what the experience,
    no matter how basic the question is,
    this community will help you.