EN
JavaScript - replace entire HTML node
7
points
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>