Home  >  Article  >  Web Front-end  >  How to Get the Entire Document HTML as a String in JavaScript?

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

Susan Sarandon
Susan SarandonOriginal
2024-11-02 11:18:30441browse

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

How to Get the Entire Document HTML as a String in JavaScript

In JavaScript, it is possible to retrieve the entire HTML content within the tags as a string. This can be achieved by following either of the methods described below:

Method 1: innerHTML Property

To obtain only the HTML within the tags, you can use the .innerHTML property of the root element:

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

Method 2: outerHTML Property

If you need to retrieve the entire HTML, including the tag itself, you can use the .outerHTML property:

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

These methods provide a simple way to access the entire document's HTML content as a string, which can be useful for various purposes such as scraping or programmatic manipulation.

The above is the detailed content of How to Get the Entire Document HTML 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