0

// navigation.js

export class Navigation extends HTMLElement {
  connectedCallback() {
    const NAVIGATION = document.querySelector("#NAVIGATION");
    this.attachShadow({ mode: "open" });
    this.shadowRoot.append(NAVIGATION.content.cloneNode(true));
  }
}

customElements.define("nav-component", Navigation);

//

// Other JS file - main.js
// HTML include
window.addEventListener("load", function () {
  const allElements = document.getElementsByTagName("*");
  Array.prototype.forEach.call(allElements, function (element) {
    const includePath = element.dataset.includePath;
    if (includePath) {
      const xhttp = new XMLHttpRequest();
      xhttp.onreadystatechange = function () {
        if (this.readyState == 4 && this.status == 200) {
          element.outerHTML = this.responseText;
        }
      };
      xhttp.open("GET", includePath, true);
      xhttp.send();
    }
  });
});

import { Navigation } from "./jsComponents/navigation.js";
<!-- navigation.html -->

<template id="NAVIGATION">
  <nav>
    <ul class="nav">
      <li class="navList">
        <a class="navAnchor" href="#">SHOP</a>
      </li>
      <li class="navList">
        <a class="navAnchor" href="#">ABOUT</a>
      </li>
    </ul>
  </nav>
</template>



<!-- other HTML - import.html -->
<!-- I want to import navigation.html into this test.html -->

<!DOCTYPE html>
<html lang="en">
  <head>
    <script src="../../script/main.js" type="module" defer></script>
    <title>test</title>
  </head>
  <body>
    <header data-include-path="navigation.html">
       <nav-component></nav-component>
     </header>
  </body>
</html>

I want to import navigation.html into this test.html. BUT, NO PRINT OUT NAV.

Open developer tools and check, it comes out like this

<nav-component>
    #shadow-root (open) 
</nav-component>

But, I can't see the content in nav-component.

The code in main.js was obtained through Googling. I also tried using jQuery, but the response was the same. I thought it was a problem with the navigation.js code and tried to write it separately, but there was no problem. There is probably a problem in main.js. But I can't figure out what the problem is.

How can I import html into other html? Or please let me know if there is any other way to import the html.

[Console error is]

Uncaught TypeError: Cannot read properties of null (reading 'content')
    at Navigation.connectedCallback (navigation.js:5:39)
    at navigation.js:36:16

navigation.js:5:39 is

 this.shadowRoot.append(NAVIGATION.content.cloneNode(true));

navigation.js:36:16 is

customElements.define("nav-component", Navigation);

and

Failed to load resource: the server responded with a status of 404 (Not Found) 
-> navigation.html
moeyg
  • 41
  • 4

0 Answers0