How to include HTML

Learn how to include HTML fragments in HTML.

HTML

Save the HTML to be included into .html file:

content.html

<a href="howto_google_maps.asp">Google Maps</a><br>
<a href="howto_css_animate_buttons.asp">Animated Buttons</a><br>
<a href="howto_css_modals.asp">Modal Boxes</a><br>
<a href="howto_js_animate.asp">Animations</a><br>
<a href="howto_js_progressbar.asp">Progress Bars</a><br>
<a href="howto_css_dropdown.asp">Hover Dropdowns</a><br>
<a href="howto_js_dropdown.asp">Click Dropdowns</a><br>
<a href="howto_css_table_responsive.asp">Responsive Tables</a><br>

to include HTML

Use w3-include-html attributes to include HTML:

Example

<div w3-include-html="content.html"></div>

Add JavaScript

HTML inclusion is done by JavaScript.

Example

<script>
function includeHTML() {
  var z, i, elmnt, file, xhttp;
  /* Traverse the collection of all HTML elements: */
  z = document.getElementsByTagName("*");
  for (i = 0; i < z.length; i++) {
    elmnt = z[i];
    /* Search for elements with a specific attribute: */
    file = elmnt.getAttribute("w3-include-html");
    if (file) {
      /* Use the attribute value as the filename to send an HTTP request: */
      xhttp = new XMLHttpRequest();
      xhttp.onreadystatechange = function() {
        if (this.readyState == 4) {
          if (this.status == 200) {elmnt.innerHTML = this.responseText;}
          if (this.status == 404) {elmnt.innerHTML = "Page not found.";}
          /* Remove attribute and call this function again: */
          elmnt.removeAttribute("w3-include-html");
          includeHTML();
        }
      }
      xhttp.open("GET", file, true);
      xhttp.send();
      /* Exit function: */
      return;
    }
  }
}
</script>

Call at the bottom of the page includeHTML():

Example

<script>
includeHTML();
</script>

Try It Yourself

Include multiple HTML snippets

You can include any number of HTML snippets:

Example

<div w3-include-html="h1.html"></div>
<div w3-include-html="content.html"></div>

Try It Yourself