Paul
Paul

Reputation: 529

Convert an Entire HTML Page to a Single JavaScript String


I need to turn an entire HTML document into one, valid JavaScript string.

This is a process that will need to be done regularly. For example:


This:

<html>
    <!--here is my html-->
    <div id="Main">some content</div>
    </html>

needs to become this:

var htmlString="<html><!--here is my html --><div id=\"Main\">some content</div><html>"

Based on what I've ready my initial thought is to read the contents of the file with Java and write my own parser. I don't think this would be possible with a shell script or the like? (I'm on OSX)

Can someone recommend a good approach?

Similar Questions I've Read
Reading entire html file to String?
convert html to javascript

Upvotes: 2

Views: 5455

Answers (2)

Jaykumar Patel
Jaykumar Patel

Reputation: 27614

Try this live, jsFiddle

JS

var htmlString = document.getElementsByTagName('html')[0].innerHTML;
console.log(htmlString);

HTML

<p>Hello</p>
<div>Hi div</div>

Upvotes: 4

Latheesan
Latheesan

Reputation: 24116

How about a jQuery GET request?

e.g.

$.get( "http://www.domain.com/some/page.html", function( data ) {
    // data == entire page in html string
});

It will work on php script also (resulting html output that is).


Alternatively, if you want to achieve this PHP, something like this will also work:

<?php

$html_str = file_get_contents('http://www.domain.com/some/page.html');

?>

Upvotes: 1

Related Questions