Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

410
Vistas
Insert header and footer on all webpages using javascript

I have created index.html file and added header and footer sections. I want to show them on my other pages like about, contact but I don't want to copy them on all webpages. Please guide me how can I do it using vanilla JavaScript.

about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

Copy your header and footer code to header.txt and footer.txt files and then just add this code to your JavaScript file. Don't forget to:

  • include JavaScript file to those pages where you want to show header and footer.
  • check path for header and footer txt files.

You can also add header and footer code to separate JavaScript files as you like.

const fetchHeader = async () => {
  try {
    const res = await fetch("./header.txt");
    const template = await res.text();
    const parse = new DOMParser();
    const html = parse.parseFromString(template, "text/html");
    const header = html.querySelector("body header");

    document.body.prepend(header);
  } catch (err) {
    console.log(err);
  }
};

const fetchFooter = async () => {
  try {
    const res = await fetch("./footer.txt");
    const template = await res.text();
    const parse = new DOMParser();
    const html = parse.parseFromString(template, "text/html");
    const footer = html.querySelector("body footer");

    document.body.append(footer);
  } catch (err) {
    console.log(err);
  }
};

fetchHeader().then(fetchFooter);

If you want to add any kind of functionality like toggling menu on click, you can do this:

const getElements = () => {
  const nav = document.querySelector(".navbar");
  const menuBtn = document.querySelector("#menu-btn");

  menuBtn.addEventListener("click", () => {
    nav.classList.toggle("active");
  });

  window.addEventListener("scroll", () => {
    nav.classList.remove("active");
  });
};

Now call this function after calling fetchHeader function because menu is in header

fetchHeader().then(getElements).then(fetchFooter);
// OR
fetchHeader().then(getElements);
fetchFooter();
about 4 years ago · Juan Pablo Isaza Denunciar

0

You can use custom elements, by now it should be supported by major browsers:

<html>
    <head>
        <script src="./custom-elements.js"></script>
    </head>
    <body>
        <app-header></app-header>
    </body>
</html>
// custom-elements.js
class AppHeader extends HTMLElement {
    connectedCallback() {
        this.innerHTML = `
            <div style='border:2px solid red; padding:5px'>
                This is my header
            </div>
        `
    }
}
window.customElements.define('app-header', AppHeader)

https://developer.mozilla.org/en-US/docs/Web/Web_Components

about 4 years ago · Juan Pablo Isaza Denunciar

0

Another may be simpler way of writing JavaScript

const headerElement = document.querySelector("header");
const footerElement = document.querySelector("footer");

const fetchHeader = async () => {
  try {
    const res = await fetch("./header.txt");
    const template = await res.text();

    headerElement.innerHTML = template;
  } catch (err) {
    console.log(err);
  }
};

const fetchFooter = async () => {
  try {
    const res = await fetch("./footer.txt");
    const template = await res.text();

    footerElement.innerHTML = template;
  } catch (err) {
    console.log(err);
  }
};

fetchHeader();
fetchFooter();
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda