Question:
It is necessary to write the source code of the page (Dom) into the variable as a string. Please tell me how you can implement this?
Answer:
The source code itself is easiest to get directly from the server (or from the cache):
Unfortunately, this will not work in a snippet.
fetch(location.href)
.then(res => res.text())
.then(res => console.log(res));
If you're interested in the already parsed DOM, there are different ways to get that.
Without <html>
:
document.getElementsByTagName('html')[0].innerHTML
document.documentElement.innerHTML
With html
(but without <!doctype
):
document.getElementsByTagName('html')[0].outerHTML
document.documentElement.outerHTML
Fully:
let html = new XMLSerializer().serializeToString(document);
console.log(html);
<!doctype html>
<html>
<head><title>Test</title></head>
<body>
<h2>Hello, world</h2>
</body>
</html>
<script>let a = 2;</script>
As you can see, the last <script>
ended up inside the body
, i.e. we get the result after parsing the browser source code.