Languages
[Edit]
EN

JavaScript - replace entire HTML node

7 points
Created by:
Lani-Skinner
748

In this short article, we would like to show a simple way how to replace entire <html> node using JavaScript.

Quick solution:

var writer = document.open('text/html', 'replace');

writer.write('<!doctype html><html><body>Hello World!</body></html>');
writer.close();

 

Practical example

In this solution old HTML source code is overwritten by new one.

// ONLINE-RUNNER:browser;

<!doctype html>
<html>
<body>
  <script>

    var writer = document.open('text/html', 'replace');

    writer.write('<!doctype html><html><body>Hello World!</body></html>');
    writer.close();

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

 

Alternative solution

In this solution old HTML element is replaced by new one.

// ONLINE-RUNNER:browser;

<!doctype html>
<html>
<body>
  <script>

    var html = document.createElement('html');
    html.innerHTML = '<body>Hello World!</body>';

    document.replaceChild(html, document.documentElement);

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

 

Alternative titles

  1. JavaScript - replace entire HTML 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