Home >Web Front-end >JS Tutorial >How to Get the HTML Content of a Document as a String in JavaScript?

How to Get the HTML Content of a Document as a String in JavaScript?

Patricia Arquette
Patricia ArquetteOriginal
2024-10-29 17:51:02718browse

How to Get the HTML Content of a Document as a String in JavaScript?

Obtaining the Document HTML as a String

In JavaScript, retrieving the entire HTML content within the tags as a string is possible through the document.documentElement object. This object represents the root HTML element of the document. Here's how you can approach it:

To access the HTML content within the root element, utilize the innerHTML property:

<code class="js">const txt = document.documentElement.innerHTML;
alert(txt);</code>

This approach returns the HTML content excluding the tags themselves.

Alternatively, to retrieve the tag including its content, employ the outerHTML property:

<code class="js">const txt = document.documentElement.outerHTML;
alert(txt);</code>

Both methods provide effective ways to obtain the HTML content of a document as a string.

The above is the detailed content of How to Get the HTML Content of a Document as a String in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn