Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

409
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda