Get HTML Content With Javascript Fetch (Simple Example)

Welcome to a quick tutorial and example of how to get HTML content using the Javascript Fetch API. So you are wondering if fetch() can get HTML content just like XMLHttpRequest? Of course, we can.

To get HTML content with the Javascript Fetch API, simply make a fetch() call to the script and return the result as text.

  • fetch("PAGE.HTML")
  • .then(res => res.text())
  • .then(html => document.getElementById("ID").innerHTML = html);

That covers the quick basics, but read on if you need the full example!

 

 

TLDR – QUICK SLIDES

[web_stories_embed url=”https://code-boxx.com/web-stories/get-html-javascript-fetch/” title=”Get HTML Content With Javascript Fetch” poster=”https://code-boxx.com/wp-content/uploads/2021/11/STORY-JS-20230518.webp” width=”360″ height=”600″ align=”center”]

Fullscreen Mode – Click Here

 

TABLE OF CONTENTS

 

 

JAVASCRIPT FETCH CONTENT

All right, let us now get into the example of getting HTML content using Javascript fetch.

 

PART 1) THE HTML

1-fetch-content.html
<div id="demo"></div>
<input type="button" value="Load Content" onclick="loadContent()">

No sweat. Just a <div id="demo"> to put the loaded contents into, and a <input type="button"> to run the fetch content demo.

 

PART 2) THE JAVASCRIPT

1-fetch-content.html
function loadContent () {
  // (A) FETCH "DUMMY.HTML"
  fetch("2-dummy.html")
 
  // (B) RETURN THE RESULT AS TEXT
  .then(res => {
    if (res.status != 200) { throw new Error("Bad Server Response"); }
    return res.text();
  })
 
  // (C) PUT LOADED CONTENT INTO <DIV>
  .then(html => document.getElementById("demo").innerHTML = html)
 
  // (D) HANDLE ERRORS - OPTIONAL
  .catch(err => console.error(err));
}

Right, this is pretty much the “expanded version” of the introduction snippet.

  1. Here, we are making a call to 2-dummy.html. It can be whatever server-side script (PHP, ASP, Python, etc… ) in your own project.
  2. Take note of if (result.status != 200) { THROW ERROR }. For the uninitiated, fetch() will consider it a success as long as the server responds. That is, even when the server returns a funky 500 (internal server error), 404 (not found), or whatever else server error. We are just doing a manual 200 (OK) check here before returning the contents fetched from the server.
  3. Captain Obvious, put the fetched contents in the <div>.
  4. Lastly, handle any errors that may have happened. Optional, but highly recommended.

 

 

PART 3) DUMMY HTML

2-dummy.html
<p>FOO!</p>

Yep. Just dummy HTML. This can be your own server-side script that generates HTML.

 

DOWNLOAD & NOTES

Here is the download link to the example code, so you don’t have to copy-paste everything.

 

SORRY FOR THE ADS...

But someone has to pay the bills, and sponsors are paying for it. I insist on not turning Code Boxx into a "paid scripts" business, and I don't "block people with Adblock". Every little bit of support helps.

Buy Me A Coffee Code Boxx eBooks

 

EXAMPLE CODE DOWNLOAD

Click here for the source code on GitHub gist, just click on “download zip” or do a git clone. I have released it under the MIT license, so feel free to build on top of it or use it in your own project.

 

EXTRA BITS & LINKS

That’s all for the tutorial, and here is a small section on some extras and links that may be useful to you.

 

RETURN AS OTHER DATA TYPES?

The sharp code ninjas should have immediately noticed return result.text(). So, does that mean fetch() is capable of dealing with other data types? The answer is yes.

  • arrayBuffer()
  • blob()
  • formData()
  • json()

 

 

FETCHING HTML FROM ANOTHER SITE?

  • Please take note that there is something called “same origin policy” – By default, site-a.com can only make fetch calls to site-a.com.
  • If you want to make a fetch from site-a.com to site-b.com, this is called “cross origins” (CORS for short).
  • It is possible to make a CORS fetch – But only if you own both sites, or the other website is open to let your site access. See the CORS fetch link below.

 

COMPATIBILITY CHECKS

Will not have any problems on all modern browsers.

 

LINKS & REFERENCES

 

INFOGRAPHIC CHEAT SHEET

Get HTML Content With JS Fetch (Click To Enlarge)

 

THE END

Thank you for reading, and we have come to the end. I hope that it has helped you to better understand, and if you want to share anything with this guide, please feel free to comment below. Good luck and happy coding!

2 thoughts on “Get HTML Content With Javascript Fetch (Simple Example)”

  1. Matthew Schneider

    So opening this from my _file system_ results in a CORS (Cross-Origin Resource Sharing) error.

    “CORS requests may only use the HTTP or HTTPS URL scheme, but the URL specified by the request is of a different type. This often occurs if the URL specifies a local file, using the file:/// scheme.” https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS/Errors/CORSRequestNotHttp

    Probably not a surprise. I should be running this on a server (e.g. localhost) using HTTP scheme.

    This might be a stumper for some. Maybe consider including a note in your tutorial? Regardless, thanks for the nice little tutorial.

    Matt

Leave a Comment

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