Top community members
All Wiki Articles Create Wiki Article

Have you ever heard about encyclopedia for code?

What about: Wiki for Code project?

* because I've tried to share code and my solutions on different services and it was removed or I was unwelcomed
   - maybe it wasn't good place, but this one is.

if you think you have solution that can help someone, you are welcome to share this solution - Click here

JavaScript - how to get html of whole webpage?

0 contributions
12 points

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.

0 contributions

Checkout latest Findings & News:

Checkout latest questions:

Checkout latest wiki articles:

Hey 👋
Would you like to know what we do?
  • Dirask is IT community, where we share coding knowledge and help each other to solve coding problems.
  • We welcome everyone,
    no matter what the experience,
    no matter how basic the question is,
    this community will help you.
Read more