How do I load an HTML page in a div using JavaScript?

Solution 1:

I finally found the answer to my problem. The solution is

function load_home() {
     document.getElementById("content").innerHTML='<object type="text/html" data="home.html" ></object>';
}

Solution 2:

You can use the jQuery load function:

<div id="topBar">
    <a href ="#" id="load_home"> HOME </a>
</div>
<div id ="content">        
</div>

<script>
$(document).ready( function() {
    $("#load_home").on("click", function() {
        $("#content").load("content.html");
    });
});
</script>

Sorry. Edited for the on click instead of on load.

Solution 3:

Fetch API

function load_home (e) {
    (e || window.event).preventDefault();

    fetch("http://www.yoursite.com/home.html" /*, options */)
    .then((response) => response.text())
    .then((html) => {
        document.getElementById("content").innerHTML = html;
    })
    .catch((error) => {
        console.warn(error);
    });
} 

XHR API

function load_home (e) {
  (e || window.event).preventDefault();
  var con = document.getElementById('content')
  ,   xhr = new XMLHttpRequest();

  xhr.onreadystatechange = function (e) { 
    if (xhr.readyState == 4 && xhr.status == 200) {
      con.innerHTML = xhr.responseText;
    }
  }

  xhr.open("GET", "http://www.yoursite.com/home.html", true);
  xhr.setRequestHeader('Content-type', 'text/html');
  xhr.send();
}

based on your constraints you should use ajax and make sure that your javascript is loaded before the markup that calls the load_home() function

Reference - davidwalsh

MDN - Using Fetch

JSFIDDLE demo

Solution 4:

Fetching HTML the modern Javascript way

This approach makes use of modern Javascript features like async/await and the fetch API. It downloads HTML as text and then feeds it to the innerHTML of your container element.

/**
  * @param {String} url - address for the HTML to fetch
  * @return {String} the resulting HTML string fragment
  */
async function fetchHtmlAsText(url) {
    return await (await fetch(url)).text();
}

// this is your `load_home() function`
async function loadHome() {
    const contentDiv = document.getElementById("content");
    contentDiv.innerHTML = await fetchHtmlAsText("home.html");
}

The await (await fetch(url)).text() may seem a bit tricky, but it's easy to explain. It has two asynchronous steps and you could rewrite that function like this:

async function fetchHtmlAsText(url) {
    const response = await fetch(url);
    return await response.text();
}

See the fetch API documentation for more details.