How to load HTML file contents to div with JavaScript?

Sometimes, we want to load HTML file contents to div with JavaScript.

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

How to load HTML file contents to div with JavaScript?

To load HTML file contents to div with JavaScript, we use fetch.

For instance, we write

const loadHtml = async () => {
  const response = await fetch("page.html");
  const text = await response.text();
  document.getElementById("elementID").insertAdjacentText("beforeend", text);
};

loadHtml();

to define the loadHtml function.

In it, we call fetch to get the content of page.html.

We get it as a string with response.text.

And then we call insertAdjacentText to insert the HTMLK into the element we selected with getElementById.

Conclusion

To load HTML file contents to div with JavaScript, we use fetch.