Categories
JavaScript Answers

How to get HTML code using JavaScript with a URL?

Spread the love

Sometimes, we want to get HTML code using JavaScript with a URL.

In this article, we’ll look at how to get HTML code using JavaScript with a URL.

How to get HTML code using JavaScript with a URL?

To get HTML code using JavaScript with a URL, we can use the fetch function.

For instance, we write:

(async () => {
  const response = await fetch('https://jsfiddle.net/');
  const template = await response.text();
  console.log(template);
})();

We call fetch with the URL of the HTML we want to get.

Then we call response.text to get the response string from the response object.

This only works with the URLs that are in the same domain that the script is hosted in.

Conclusion

To get HTML code using JavaScript with a URL, we can use the fetch function.

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 *