Simple way would be to put the header part in a separate html file.

Now load this file in html code using jQuery load function like

$("#headerDiv").load("header.html")

Know that, this will require web server because load function sends a request to server.

Check out the code sample:

demo.html

<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<script> 
   $(function(){
    $("#headerDiv").load("header.html");
   });  
</script>
</head>
<body>
<div id="headerDiv"></div>
<!-- Rest of the code -->
</body>
</html>

header.html

<div >
    <a>something</a>
    <a>something</a>        
</div>
Answer from pritesh on Stack Overflow
🌐
W3Schools
w3schools.com › w3js › w3js_html_include.asp
W3.JS HTML Includes
HTML includes are done by JavaScript. Make sure your page has w3.js loaded and call w3.includeHTML():
Top answer
1 of 4
9

Simple way would be to put the header part in a separate html file.

Now load this file in html code using jQuery load function like

$("#headerDiv").load("header.html")

Know that, this will require web server because load function sends a request to server.

Check out the code sample:

demo.html

<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<script> 
   $(function(){
    $("#headerDiv").load("header.html");
   });  
</script>
</head>
<body>
<div id="headerDiv"></div>
<!-- Rest of the code -->
</body>
</html>

header.html

<div >
    <a>something</a>
    <a>something</a>        
</div>
2 of 4
5

That is called HTML includes, and YES, it is possible

<div w3-include-HTML="content.html">My HTML include will go here.</div>
<script>
(function () {
  myHTMLInclude();
  function myHTMLInclude() {
    var z, i, a, file, xhttp;
    z = document.getElementsByTagName("*");
    for (i = 0; i < z.length; i++) {
      if (z[i].getAttribute("w3-include-html")) {
        a = z[i].cloneNode(false);
        file = z[i].getAttribute("w3-include-html");
        var xhttp = new XMLHttpRequest();
        xhttp.onreadystatechange = function() {
          if (xhttp.readyState == 4 && xhttp.status == 200) {
            a.removeAttribute("w3-include-html");
            a.innerHTML = xhttp.responseText;
            z[i].parentNode.replaceChild(a, z[i]);
            myHTMLInclude();
          }
        }      
        xhttp.open("GET", file, true);
        xhttp.send();
        return;
      }
    }
  }
})();
</script>

NOTES

HTML doesn't have a simple include mechanism (except for frames like iframe, which have side effects).

A better solution would be to use Server-Side includes, which is the preferred way of adding common parts to your document, on the server, of course.

Discussions

HTML5 - Why does my w3-include-html tag not work?
Because that's not a normal html tag. It only works if you include w3school's Javascript file. More on reddit.com
🌐 r/learnprogramming
3
0
September 28, 2016
[Suggestion] w3-include-html attribute recognition
This is a suggestion, not an issue. In my website, I use the w3 include HTML script, but I think it would be nice if there could be something that would tell users that they should use iFrames as t... More on github.com
🌐 github.com
1
March 28, 2018
how to insert html into html file
Find answers to how to insert html into html file from the expert community at Experts Exchange More on experts-exchange.com
🌐 experts-exchange.com
August 4, 2017
Can't use w3school HTML include
So here's the link to the original w3school article about HTML include using their .js file link. I literally copied everything from the w3school example, but got this error : w3school.js:131 More on stackoverflow.com
🌐 stackoverflow.com
🌐
Reddit
reddit.com › r/learnprogramming › html5 - why does my w3-include-html tag not work?
r/learnprogramming on Reddit: HTML5 - Why does my w3-include-html tag not work?
September 28, 2016 -

I want to include html code (a header) in another html page (index page).

Using php (include, echo) does work, but why does the tag w3-include-html not work :/.

I used it like this:

<div w3-include-html="path/name/info/htmlcode"></div>

Reference: http://www.w3schools.com/w3css/w3data_includes.asp

🌐
W3Schools
w3schools.com › tags › ref_html_browsersupport.asp
HTML Reference Browser Support
HTML CSS JAVASCRIPT SQL PYTHON JAVA PHP HOW TO W3.CSS C C++ C# BOOTSTRAP REACT MYSQL JQUERY EXCEL XML DJANGO NUMPY PANDAS NODEJS DSA TYPESCRIPT ANGULAR ANGULARJS GIT POSTGRESQL MONGODB ASP AI R GO KOTLIN SWIFT SASS VUE GEN AI SCIPY AWS CYBERSECURITY DATA SCIENCE INTRO TO PROGRAMMING INTRO TO HTML & CSS BASH RUST · HTML by Alphabet HTML by Category HTML Browser Support ...
🌐
W3Schools
w3schools.com › howto › howto_html_include.asp
How To Include HTML
Fullscreen Video Modal Boxes Delete Modal Timeline Scroll Indicator Progress Bars Skill Bar Range Sliders Color Picker Email Field Tooltips Display Element Hover Popups Collapsible Calendar HTML Includes To Do List Loaders Badges Star Rating User Rating Overlay Effect Contact Chips Cards Flip Card Profile Card Product Card Alerts Callout Notes Labels Ribbon Tag Cloud Circles Style HR Coupon List Group List Group with Badges List Without Bullets Responsive Text Cutout Text Glowing Text Fixed Footer Sticky Element Equal Height Clearfix Responsive Floats Snackbar Fullscreen Window Scroll Drawing
🌐
GitHub
github.com › validator › validator › issues › 625
[Suggestion] w3-include-html attribute recognition · Issue #625 · validator/validator
March 28, 2018 - It occurred in my code at a line with: <div w3-include-html="../nav.html"></div>. There could be something that says Attribute "w3-include-html" should be replaced by using an "<iframe>" instead of "div".
Author   scoutchorton
Find elsewhere
🌐
W3schools-fa
w3schools-fa.ir › html › html5_browsers.html
HTML5 Browser Support - w3schools
HTML Tag Reference HTML Event Reference HTML Color Reference HTML Attribute Reference HTML Canvas Reference HTML SVG Reference HTML Character Sets Google Maps Reference · CSS Reference CSS Browser Support CSS Selector Reference Bootstrap 3 Reference Bootstrap 4 Reference W3.CSS Reference Icon ...
🌐
Experts Exchange
experts-exchange.com › questions › 29048402 › how-to-insert-html-into-html-file.html
Solved: how to insert html into html file | Experts Exchange
August 4, 2017 - <!DOCTYPE html> <html> <script src="https://www.w3schools.com/lib/w3.js"></script> <body> <div w3-include-html="content.html"></div> <script> w3.includeHTML(); </script> </body> </html>
🌐
W3Schools
www-db.deis.unibo.it › courses › TW › DOCS › w3schools › html › html5_browsers.asp.html
HTML5 Browser Support
While using this site, you agree to have read and accepted our terms of use, cookie and privacy policy. Copyright 1999-2016 by Refsnes Data. All Rights Reserved. Powered by W3.CSS. ... JavaScript Reference HTML DOM Reference jQuery Reference jQuery Mobile Reference AngularJS Reference Google Maps Reference
🌐
Beyondjava
beyondjava.net › html-includes
HTML Includes
August 5, 2017 - Beyond Java · Sitemap · Talks & Articles · Projects · Guest Posts · About · Legalese · Statistics · (opt out) · Mastodon
🌐
Stack Overflow
stackoverflow.com › questions › 75392783 › using-w3-include-html-breaks-some-tags-and-js-scripts-stop-working
Using w3-include-html breaks some tags and JS scripts stop working
I have tried removing and adding different tags on all the different HTML files, such as the head tag, no dice. I thought maybe it was just OperaGX moving my included HTML code to the body but after checking both Chrome and Edge that is not the case. I have tried using the w3-include-html by having the source script directly from the w3 website, didn't change anything.
🌐
W3schools-fa
w3schools-fa.ir › w3js › w3js_html_include.html
W3.JS Includes
HTML includes are done by JavaScript. Make sure your page has w3.js loaded and call w3.includeHTML():
🌐
GitHub
gist.github.com › h5ng › 8b072af9c730591328b91c6f2d98b371
w3-include-html · GitHub
w3-include-html · Raw · index.html · This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters ·
🌐
Can I Use
caniuse.com
Can I use... Support tables for HTML5, CSS3, etc
Each feature support table includes a "Usage relative" button. This will resize each browser version cell to be relative to the amount of support it has for the selected usage source. The CanIUse Embed — Add support tables to your site · Caniuse Component — Add support tables to your presentations ... Can I email... — Support tables for HTML & CSS in emails
Top answer
1 of 15
2

I have one more solution to do this

Using Ajax in javascript

here is the explained code in Github repo https://github.com/dupinder/staticHTML-Include

basic idea is:

index.html

<!DOCTYPE html>
<html>
<head>
    <meta charset='utf-8'>
    <meta http-equiv='X-UA-Compatible' content='IE=edge'>
    <title>Page Title</title>
    <meta name='viewport' content='width=device-width, initial-scale=1'>
    <script src='main.js'></script>


</head>
<body>
    <header></header>

    <footer></footer>
</body>
</html>

main.js

fetch("./header.html")
  .then(response => {
    return response.text()
  })
  .then(data => {
    document.querySelector("header").innerHTML = data;
  });

fetch("./footer.html")
  .then(response => {
    return response.text()
  })
  .then(data => {
    document.querySelector("footer").innerHTML = data;
  });
2 of 15
2

w3.js is pretty cool.

https://www.w3schools.com/lib/w3.js

and we are focus

w3-include-html

but consider the below case

-  popup.html
-  popup.js
-  include.js
-  partials 
   -  head
         -  bootstrap-css.html
         -  fontawesome-css.html
         -  all-css.html
   -  hello-world.html
<!-- popup.html -->
<head>
<script defer type="module" src="popup.js"></script>
<meta data-include-html="partials/head/all-css.html">
</head>

<body>
<div data-include-html="partials/hello-world.html"></div>
</body>
<!-- bootstrap-css.html -->
<link href="https://.../[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" />

<!-- fontawesome-css.html -->
<link rel="stylesheet" href="https://.../font-awesome/5.15.4/css/all.min.css" />
<!-- all-css.html -->
<meta data-include-html="bootstrap-css.html">
<meta data-include-html="fontawesome-css.html">

<!-- 
If you want to use w3.js.include, you should change as below

<meta w3-include-html="partials/head/bootstrap-css.html">
<meta w3-include-html="partials/head/fontawesome-css.html">

Of course, you can add the above in the ``popup.html`` directly.

If you don't want to, then consider using my scripts.
-->
<!-- hello-world.html -->
<h2>Hello World</h2>

Script

// include.js

const INCLUDE_TAG_NAME = `data-include-html`

/**
 * @param {Element} node
 * @param {Function} cb callback
 * */
export async function includeHTML(node, {
  cb = undefined
}) {
  const nodeArray = node === undefined ?
    document.querySelectorAll(`[${INCLUDE_TAG_NAME}]`) :
    node.querySelectorAll(`[${INCLUDE_TAG_NAME}]`)

  if (nodeArray === null) {
    return
  }

  for (const node of nodeArray) {
    const filePath = node.getAttribute(`${INCLUDE_TAG_NAME}`)
    if (filePath === undefined) {
      return
    }

    await new Promise(resolve => {
      fetch(filePath
      ).then(async response => {
          const text = await response.text()
          if (!response.ok) {
            throw Error(`${response.statusText} (${response.status}) | ${text} `)
          }
          node.innerHTML = text
          const rootPath = filePath.split("/").slice(0, -1)
          node.querySelectorAll(`[${INCLUDE_TAG_NAME}]`).forEach(elem=>{
            const relativePath = elem.getAttribute(`${INCLUDE_TAG_NAME}`) // not support ".."
            if(relativePath.startsWith('/')) { // begin with site root.
              return
            }
            elem.setAttribute(`${INCLUDE_TAG_NAME}`, [...rootPath, relativePath].join("/"))
          })
          node.removeAttribute(`${INCLUDE_TAG_NAME}`)
          await includeHTML(node, {cb})
          node.replaceWith(...node.childNodes) // https://stackoverflow.com/a/45657273/9935654
          resolve()
        }
      ).catch(err => {
        node.innerHTML = `${err.message}`
        resolve()
      })
    })
  }

  if (cb) {
    cb()
  }
}
// popup.js

import * as include from "include.js"

window.onload = async () => {
  await include.includeHTML(undefined, {})
  // ...
}

output

<!-- popup.html -->

<head>

<link href="https://.../[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" />
<link rel="stylesheet" href="https://.../font-awesome/5.15.4/css/all.min.css" />
</head>

<body>
<h2>Hello World</h2>
</body>