Categories
JavaScript Answers

How to load HTML template with JavaScript?

Spread the love

Sometimes, we want to load HTML template with JavaScript.

In this article, we’ll look at how to load HTML template with JavaScript.

How to load HTML template with JavaScript?

To load HTML template with JavaScript, we use the importNode method.

For instance, we write

<html>
  <head>
    <template>My template</template>
  </head>
  <body>
    <script>
      document.body.append(
        document.importNode(document.querySelector("template").content, true)
      );
    </script>
  </body>
</html>

to call importNode to import the template element’s content.

Then we call append to append the template element’s content into the body element as its last child.

Conclusion

To load HTML template with JavaScript, we use the importNode method.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *