How to Get the Entire Document HTML as a String

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



Leave a reply



Submit