user1196522
user1196522

Reputation: 261

Get HTML source code as a string

I want the source code of an HTML page (1.html) to be used in another page (2.html). Furthermore, I want to perform operations on it in 2.html.

Is there a way to do this?

EDIT: 1.html is a separate public webpage and I do not have access to make changes to its source code. I have to do whatever I need only by using 2.html.

Upvotes: 14

Views: 54680

Answers (6)

MaZzIMo24
MaZzIMo24

Reputation: 207

A realy simple and modern way is the follow:

fetch('1.html').then(function(response) {
    /* when the page is loaded convert it to plain text */
    return response.text()
}).then(function(html) {
    /* initialize the DOM parser */
    var initParser = new DOMParser();
    /* parse the text */
    var parse = initParser.parseFromString(html, 'text/html');
    /* you can now even select part of that html as you would in the regular DOM */ 
    /* example */
    var docOutput = parse.querySelector('html').outerHTML;
    console.log(docOutput);
}).catch(function(error) {  
    console.log('Error fetch page: ', error);  
});

Upvotes: 0

Samuele Mattiuzzo
Samuele Mattiuzzo

Reputation: 11048

To get the DOM converted to a string:

document.getElementsByTagName('html')[0].innerHTML

Question: what do you mean by "use it"? Do you need to include 1.html inside 2.html? Or do you just need to process it?

Upvotes: 23

nightf0x
nightf0x

Reputation: 2041

Use can use .html method alternatively to get the entire html data of the page.

$(function(){
    var a = ($('html').html())
})​

Upvotes: 2

Nicola Peluchetti
Nicola Peluchetti

Reputation: 76910

I don't understand whatyou mean that you must make modifications, but you could simply load the second page through AJAX

var url ="1.html";
$.ajax({
  url: url,
  dataType: 'html'
  success: function(data){
             //do something with data, which is the page 1.html
           }

});

Upvotes: 2

eozzy
eozzy

Reputation: 68740

jQuery:

$.get('ajax/test.html', function(data) {
  $('.result').html(data);
  alert('Load was performed.');
});

Upvotes: 3

Starx
Starx

Reputation: 79041

Its very simple

On 2.html use this jQuery snippet

$.get("1.html", function(response) { 
    alert(response) 
    //do you operations
});

Upvotes: 3

Related Questions