Categories
JavaScript Answers

How to return HTML with fetch() and JavaScript?

Spread the love

Sometimes, we want to return HTML with fetch() and JavaScript.

In this article, we’ll look at how to return HTML with fetch() and JavaScript.

How to return HTML with fetch() and JavaScript?

To return HTML with fetch() and JavaScript, we can use the response text method.

For instance, we write

const fetchMyDocument = async () => {
  try {
    const response = await fetch("/path/to/file.html");
    document.body.innerHTML = await response.text();
  } catch (err) {
    console.log(err);
  }
};

to call fetch to make a GET request to "/path/to/file.html".

Then we get the response from the promise returned by fetch.

Finally, we get the response body HTML from the promise returned by the response.text method with await.

Conclusion

To return HTML with fetch() and JavaScript, we can use the response text method.

Leave a Reply

Your email address will not be published.

If you like the content of this blog, subscribe to my email list to get exclusive articles not available to anyone else.