How to load another html file using JS

To dynamically load content, you could make an AJAX call using XMLHttpRequest().

In this example a url is passed to the loadPage() function, in which the loaded content is returned.

<!DOCTYPE html>
<html lang="en">
    <head>
        <script type="text/javascript">
            function loadPage(href)
            {
                var xmlhttp = new XMLHttpRequest();
                xmlhttp.open("GET", href, false);
                xmlhttp.send();
                return xmlhttp.responseText;
            }
        </script>
    </head>

    <body>
        <div onClick="document.getElementById('bottom').innerHTML = 
                      loadPage('hello-world.html');">Home</div>

        <div id="bottom"></div>
    </body>

</html>

When the div element containing text of "Home" is clicked, it sets the html of div element with id of "bottom" to content found in the "hello-world.html" document at the same relative location.

hello-world.html

<p>hello, world</p>

Tags:

Javascript