0

I simply would like to replace the <main>-Element and it's content of firstPage.html ...

// ... header of my 1st document ...

<body>
    <main>
        The content of the 1st document...
    </main>
</body>

// ... footer of my 1st document ...

... with the <main>-Element and it's content of secondPage.html ...

secondPage.html

// ... header of my 2nd document ...

<body>
    <main>
        The content of the 2nd document...
    </main>
</body>

// ... footer of my 2nd document ...

... using AJAX call by plain JavaScript. How could I do that?

I am able to several methods to load 2nd document completely into the 1st one but I can't find any solution in JavaScript to load only specific HTML-element from another URL into DOM of 1st document. :(

UPDATE/EDIT:

This is my status quo of my ajax function:

var myLoad = ( type, url, data, success ) => {

    var d = data ? ( typeof data == 'string' ) ? data : Object.keys(data).map(k=>( encodeURIComponent(k) + '=' + encodeURIComponent(data[k]) )).join('&') : '' ;
    var u = (d && type==='GET') ? url+'?'+d : url ;

    var x = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");
    x.open(type,u);
    x.onreadystatechange = () => {
        if( x.readyState > 3 && x.status == 200 ){ 
          success(x.responseText) 
        }
    };
    x.setRequestHeader('X-Requested-With','XMLHttpRequest');
    if( type === 'POST' ){
      x.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
      x.send(d);
    } else {
      x.send();
    }
    return x;
};

myLoad( 'GET', 'secondPage.html', '', r => {
  // of course this loads the whole document (secondPage.html) into <main>
  // but how to do otherwise ???
  document.querySelector('main').innerHTML = r; 
};
RE666
  • 91
  • 1
  • 9

1 Answers1

1

You could do it using the fetch API to get the HTML as text.

Then you parse it to HTML using the DOMParser to get the new HTML and add it to the old <main>.

In this case, I added the HTML as soon as the DOM was loaded (DOMContentLoaded), but you could eventually change it to whatever suits your needs:

document.addEventListener('DOMContentLoaded', DOMContentLoadedJS, false);

function DOMContentLoadedJS(event) {
    //fetch html as text
    fetch("/page2.html").then(response => response.text()).then(AfterFetchingHTML);
}

function AfterFetchingHTML(htmlText) {
    let main1 = document.querySelector("main"); //<main> on page1.html

    let htmlParser = new DOMParser();
    let htmlDoc = htmlParser.parseFromString(htmlText, "text/html");
    let main2 = htmlDoc.querySelector("main"); //main on page2.html

    //clear children from first <main>
    while (main1.firstChild) main1.removeChild(main1.firstChild);

    //add new <main>
    main1.innerHTML = main2.innerHTML;
}
FF-
  • 732
  • 9
  • 19