Skip to content

Instantly share code, notes, and snippets.

@rsgranne
Created October 31, 2023 09:10
Show Gist options
  • Save rsgranne/1cd9f6db8cdda75e283522a3c8c4c4a0 to your computer and use it in GitHub Desktop.
Save rsgranne/1cd9f6db8cdda75e283522a3c8c4c4a0 to your computer and use it in GitHub Desktop.

Revisions

  1. rsgranne created this gist Oct 31, 2023.
    36 changes: 36 additions & 0 deletions include.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,36 @@
    // Function to include HTML content below a specified element, id, or class
    function includeHTML(url, targetElement = null) {
    fetch(url)
    .then(response => response.text())
    .then(data => {
    const parser = new DOMParser();
    const htmlContent = parser.parseFromString(data, 'text/html');
    const includedContent = htmlContent.querySelector('body').childNodes;

    if (targetElement) {
    const targetElementNode = typeof targetElement === 'string'
    ? document.querySelector(targetElement)
    : targetElement;

    includedContent.forEach(node => {
    targetElementNode.insertAdjacentElement('afterend', node.cloneNode(true));
    });
    } else {
    const firstElement = document.querySelector('body').childNodes[0];
    includedContent.forEach(node => {
    firstElement.insertAdjacentElement('beforebegin', node.cloneNode(true));
    });
    }
    })
    .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.