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:
xxxxxxxxxx
1
var writer = document.open('text/html', 'replace');
2
3
writer.write('<!doctype html><html><body>Hello World!</body></html>');
4
writer.close();
In this solution old HTML source code is overwritten by new one.
xxxxxxxxxx
1
2
<html>
3
<body>
4
<script>
5
6
var writer = document.open('text/html', 'replace');
7
8
writer.write('<!doctype html><html><body>Hello World!</body></html>');
9
writer.close();
10
11
</script>
12
</body>
13
</html>
In this solution old HTML element is replaced by new one.
xxxxxxxxxx
1
2
<html>
3
<body>
4
<script>
5
6
var html = document.createElement('html');
7
html.innerHTML = '<body>Hello World!</body>';
8
9
document.replaceChild(html, document.documentElement);
10
11
</script>
12
</body>
13
</html>