walves
walves

Reputation: 2068

Is it possible to import HTML using JavaScript?

I have some html pages with the same footer. With JavaScript and only JavaScript could I import another html page inside it?

Upvotes: 15

Views: 72397

Answers (8)

Doron Saar
Doron Saar

Reputation: 486

fetch("MyHTMLFile.html").then((response) => {
  response.text().then((text) => {
    targetHTMLElement.innerHTML = text;
  });
})

Upvotes: 1

gilly3
gilly3

Reputation: 91497

Here's how you could use just javascript to add a footer to your page.

2022 code, using fetch and insertAdjacentHTML:

async function addFooter() {
    const resp = await fetch("footer.htm");
    const html = await resp.text();
    document.body.insertAdjacentHTML("beforeend", html);
}

Original 2011 code, using XMLHttpRequest and innerHTML:

var ajax = new XMLHttpRequest();
ajax.addEventListener("load", function () {
    document.body.innerHTML += ajax.responseText;
}
ajax.open("GET", "footer.htm");
ajax.send();

The 2011 code will still work in all browsers today, but fetch is more intuitive, and allows you to avoid coding an event handler callback. insertAdjacentHTML is also available for all browsers, so you could use that or innerHTML with either example. Only fetch is new, and won't work in IE without a polyfill.

Upvotes: 16

carloswm85
carloswm85

Reputation: 2397

Following this answer example (one of the answer in this question), I made this little reusable function:

/**
 * Render the array of html files, to the
 * selected container.
 * @param {*} pages - array of html file names
 * @param {*} container - HTML element name
 */
function render(pages, container) {
    const template = document.createElement("template");
    var ajax = new XMLHttpRequest();

    pages.forEach(element => {
        // this is the route where the files are stored
        ajax.open("GET", `./view/shared/${element}.html`, false);
        ajax.send();
        template.innerHTML += ajax.responseText;
    });

    document.querySelector(container).append(template.content);
}

export { render };

Which you can use in your index.js file, like so:

import { render } from "./tools/render.js";

var headerContent = ["siteName", "navbar"];

render(headerContent, "header");

This is rendering the html files siteName.html and navbar.html, into the <header> tag in the root index.html file of the site.

NOTE. This function works on localhost, but for whatever reason (which I still have to fix; I'll let you know when I do) it does not work correctly when working on GitHub Pages.

Upvotes: 1

Andrew Noyes
Andrew Noyes

Reputation: 5298

You definitely could, but if all you're doing is templating I recommend you do this on the server.

Upvotes: 0

Ricky
Ricky

Reputation: 7889

As above, one method is to use jQuery load. I happened to be doing the exact same thing now, so will post a quick example.

Using jQuery:

$("#yourDiv").load('readHtmlFromHere.html #readMe');

And your readHtmlFromHere.html page would consist of:

<div><div id="readMe"><p>I'm some text</p></div></div>

Upvotes: 9

Brad Christie
Brad Christie

Reputation: 101614

Along with what @Alex mentioned, jQuery has a method .load() that you can use to fetch a specific portion of a page (See Loading Page Fragments heading on that page). You specify the URL you want to retrieve along with a selector (so if you wanted only a specific <DIV>'s contents for instance).

Upvotes: 2

Stephan
Stephan

Reputation: 1565

You could do a server side include, depending on your webserver. but the quickest way would probably be to create a JavaScript file that uses document.write or similar to output the html syntax. and then just include the created JavaScipt file the normal way. more info at: http://webdesign.about.com/od/ssi/a/aa052002a.htm

Upvotes: 0

Alex
Alex

Reputation: 7374

You can use ajax to return a whole HTML page. If you wanted to replace the whole page you could replace the body tag and all it's children currently on the page with the body tag returned from the ajax call.

If you wanted to just replace a section you'd have to write a server-side script to create that section, then use ajax as above but just replace an element rather than the whole page.

Upvotes: 3

Related Questions