Skip to content

Instantly share code, notes, and snippets.

@rsgranne
Last active May 13, 2026 21:19
Show Gist options
  • Select an option

  • Save rsgranne/1cd9f6db8cdda75e283522a3c8c4c4a0 to your computer and use it in GitHub Desktop.

Select an option

Save rsgranne/1cd9f6db8cdda75e283522a3c8c4c4a0 to your computer and use it in GitHub Desktop.
Function to include HTML content below a specified element, id, or class
// Function to include HTML content below a specified element, id, or class
function includeHTML(url, targetElement = null) {
// Fetch the external HTML file
fetch(url)
// Convert the response from the server into plain text
.then(response => response.text())
// Work with the HTML text after it has been loaded
.then(data => {
// Create a parser that can turn a string of HTML into real HTML elements
const parser = new DOMParser();
// Parse the fetched HTML text as an HTML document
const htmlContent = parser.parseFromString(data, 'text/html');
// Get only the actual HTML elements inside the fetched file’s <body>
// This skips whitespace, line breaks, comments, and text nodes
const includedContent = htmlContent.querySelector('body').children;
// Create a temporary container for the included elements
// This lets us insert everything at once while keeping the correct order
const fragment = document.createDocumentFragment();
// Copy each included element into the temporary fragment
Array.from(includedContent).forEach(node => {
fragment.appendChild(node.cloneNode(true));
});
// If the user provided a target element, selector, id, or class
if (targetElement) {
// If targetElement is a string, use it as a CSS selector
// Examples: 'main', '#main', '.main'
//
// If targetElement is already an element, use it directly
const targetElementNode = typeof targetElement === 'string'
? document.querySelector(targetElement)
: targetElement;
// Insert the included content after the target element
targetElementNode.after(fragment);
} else {
// If no target element was provided, find the first element in <body>
const firstElement = document.querySelector('body').children[0];
// Insert the included content before the first element in <body>
firstElement.before(fragment);
}
})
// Show an error in the console if the file cannot be fetched or inserted
.catch(error => console.error('Error fetching the file:', error));
}
// To use, include `<script src="/js/include.js"></script>` in the `<head>` (or at least above where you call the `includeHTML` function) & then place this in `<body>`:
//
// <script>
// includeHTML('/includes/footer.html', 'main');
// </script>
//
// Replace `/includes/footer.html` with the file you want to insert.
//
// Replace `main` with either an element (like `main`), an id (`#main`), or a class (`.main`), & the included file will be placed below it.
@rsgranne
Copy link
Copy Markdown
Author

Fix HTML include script to preserve element order. Use a DocumentFragment to insert included HTML as a group, which prevents multiple top-level elements from being inserted in reverse order. Also use children instead of childNodes so whitespace, comments, and text nodes are ignored before insertion. Added more detailed comments for learning.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment