How to include html file in html

Learn how to include HTML snippets in HTML.

The HTML

Save the HTML you want to include in an .html file:

content.html

Google Maps

Animated Buttons

Modal Boxes

Animations

Progress Bars

Hover Dropdowns

Click Dropdowns

Responsive Tables

Include the HTML

Including HTML is done by using a w3-include-html attribute:

Example

Add the JavaScript

HTML includes are done by JavaScript.

Example


function includeHTML[] {
  var z, i, elmnt, file, xhttp;
  /* Loop through a collection of all HTML elements: */
  z = document.getElementsByTagName["*"];
  for [i = 0; i < z.length; i++] {
    elmnt = z[i];
    /*search for elements with a certain atrribute:*/
    file = elmnt.getAttribute["w3-include-html"];
    if [file] {
      /* Make an HTTP request using the attribute value as the file name: */
      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 the attribute, and call this function once more: */
          elmnt.removeAttribute["w3-include-html"];
          includeHTML[];
        }
      }
      xhttp.open["GET", file, true];
      xhttp.send[];
      /* Exit the function: */
      return;
    }
  }
}

Call includeHTML[] at the bottom of the page:

Include Many HTML Snippets

You can include any number of HTML snippets:

Example


Try it Yourself »


w3.js is pretty cool.

//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


















Hello World

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] // //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










Hello World

Can we include HTML file in HTML?

Embedding an HTML file is simple. All we need to do is use the common „“ element. Then we add the value „import“ to the „rel“ attribute. Using „href“ we attach the URL of the HTML file, just like we are used to when it comes to stylesheets and scripts.

How do you insert a file in HTML?

The defines a file-select field and a "Browse" button for file uploads. To define a file-select field that allows multiple files to be selected, add the multiple attribute. Tip: Always add the tag for best accessibility practices!

How do you display a file in HTML?

HTML Editors.
Step 1: Open Notepad [PC] Windows 8 or later: ... .
Step 1: Open TextEdit [Mac] Open Finder > Applications > TextEdit. ... .
Step 2: Write Some HTML. Write or copy the following HTML code into Notepad: ... .
Step 3: Save the HTML Page. Save the file on your computer. ... .
Step 4: View the HTML Page in Your Browser..

How do I display the content of one HTML page in another?

HTML Iframe Syntax The HTML tag specifies an inline frame. An inline frame is used to embed another document within the current HTML document.

Chủ Đề