How to get the entire document HTML as a string?
MS added the outerHTML
and innerHTML
properties some time ago.
According to MDN, outerHTML
is supported in Firefox 11, Chrome 0.2, Internet Explorer 4.0, Opera 7, Safari 1.3, Android, Firefox Mobile 11, IE Mobile, Opera Mobile, and Safari Mobile. outerHTML
is in the DOM Parsing and Serialization specification.
See quirksmode for browser compatibility for what will work for you. All support innerHTML
.
var markup = document.documentElement.innerHTML;
alert(markup);
How do I get the entire HTML document as a string excluding some elements?
I'd probably clone the whole tree, then remove the elements you don't want:
var clone = document.body.cloneNode(true);
clone.querySelectorAll(".exclude").forEach(function(element) {
element.parentNode.removeChild(element);
});
var html = clone.outerHTML;
Note that this assumes body
, itself, doesn't have the exclude
class.
Example:
var clone = document.body.cloneNode(true);// Snippet-specific: Also remove the scriptclone.querySelectorAll(".exclude, script").forEach(function(element) { element.parentNode.removeChild(element);});var html = clone.outerHTML;console.log(html);
<div> I want this <div>And this</div></div><div class="exclude"> I don't want this <div>Or this, since its parent is excluded</div></div>
Get the whole document's html with JavaScript/JQuery
This will get you all the HTML:
document.documentElement.outerHTML
Unfortunately it does not return the doctype. But you can use document.doctype
to get it and glue the two together.
how can I convert a document (html) to a string var in js?
You can try this: document.getElementsByTagName('html')[0].innerHTML
, this will output all the current html for the page as a string for you.
Get entire text of document as a string using javascript
Maybe you want to traverse all the nodes of the DOM? You can do this with document.childNodes, working recursively with each node.
Related Topics
Submit Form Without Page Reloading
How to Modify the Url Without Reloading the Page
How to Send Formdata Objects With Ajax-Requests in Jquery
Why Does My Http://Localhost Cors Origin Not Work
Get Dom Content of Cross-Domain Iframe
Make Iframe Automatically Adjust Height According to the Contents Without Using Scrollbar
Vue.Js Dynamic Images Not Working
Html Script Tag: Type or Language (Or Omit Both)
How to Scroll to an Element Inside a Div
Use Html5 to Resize an Image Before Upload
How to Prevent Unicode Characters from Rendering as Emoji in HTML from JavaScript
Simulation Background-Size: Cover in Canvas
Zoom in on a Point (Using Scale and Translate)
Non-Standard Attributes on HTML Tags. Good Thing? Bad Thing? Your Thoughts
Why Are Duplicate Id Values Not Allowed in Html