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

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

DDD
Release: 2024-10-29 09:17:02
Original
536 people have browsed it

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

Accessing the Full Document HTML as a String

In JavaScript, you can obtain the complete HTML within the tags as a string. Typically, this method is employed to facilitate tasks such as scraping web pages or capturing the document's current state for logging or debugging purposes.

Solution:

Regardless of which approach you choose, the process involves retrieving the root element, referenced as document.documentElement.

Using innerHTML:
If your goal is to obtain the HTML content within the tags, excluding the tag itself, leverage the .innerHTML attribute:

const html = document.documentElement.innerHTML;
Copy after login

This method returns a string containing the entire HTML content between the and tags.

Using outerHTML:
Conversely, if you desire to capture the tag along with its content, utilize the .outerHTML attribute:

const html = document.documentElement.outerHTML;
Copy after login

This method yields a string encompassing both the tag and the HTML content it encapsulates.

These string representations of the document's HTML can be assigned to a variable for further processing, manipulation, or display.

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

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template