Languages
[Edit]
EN

JavaScript - how to get html of whole webpage?

12 points
Created by:
p_agon
409

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.

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