Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript / Jquery HTML Export DOM Structure/Page to HTML File or Text

I want to modify through the dom various element properties and then save that page as an html file. View source doesn't always reflect dom adjustments. Is there a way to write the whole page to a file or otherwise get the updated source page into a file?

like image 843
Matt Ralston Avatar asked Jun 21 '11 15:06

Matt Ralston


People also ask

What is parseHTML in JavaScript?

parseHTML uses native methods to convert the string to a set of DOM nodes, which can then be inserted into the document. These methods do render all trailing or leading text (even if that's just whitespace).

How to get the whole HTML element in JavaScript?

If you want to find all HTML elements that match a specified CSS selector (id, class names, types, attributes, values of attributes, etc), use the querySelectorAll() method. This example returns a list of all <p> elements with class="intro" .

How do I export a HTML file?

Click File > Export > To HTML. The Web Wizard appears. In the Report tab, specify whether to export the report result to a single HTML file or multiple HTML files. By default the name of the report is used as the name of the exported HTML file.

How do I get HTML using jQuery?

To get HTML content of an element using jQuery, use the html() method. The html() method gets the html contents of the first matched element.


2 Answers

I'm thinking this should do the trick for ya.

$('html').html();

JavaScript can't write files when being ran from a browser (security). But you can send this to a PHP script and write it to a file from there. For example:

$.post('write.php', { dom : $('html').html() });

write.php

file_put_contents('new.html', urldecode($_POST['dom']));
like image 147
John Strickler Avatar answered Oct 21 '22 14:10

John Strickler


In newish browsers (IE 10, FF 20, Chrome 26, Safari 6, Opera 15), you can create a Blob and save it into a file using window.URL.createObjectURL.

Demo, Reference:

objectURL = window.URL.createObjectURL(blob);
  • Where blob is a File object or a Blob object to create a URL object for.
  • objectURL is the generated object URL. The entire contents of the specified file are represented by the text of the URL. It can then be used in window.open.

Example of a Blob:

var parts = ["<p class=\"paragraph\"><a id=\"link\">hey!<\/a><\/p>"];
new Blob(parts, { "type" : "text\/html" });

To list current Blobs in Chrome execute the following in your address bar:

chrome://blob-internals
like image 24
Radek Avatar answered Oct 21 '22 12:10

Radek