How To 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((result) => { return result.text(); })
  • .then((content) => { document.getElementById("ID").innerHTML = content; });

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

ⓘ I have included a zip file with all the source code at the start of this tutorial, so you don’t have to copy-paste everything… Or if you just want to dive straight in.

 

 

QUICK SLIDES

 

TABLE OF CONTENTS

Download & Notes Fetch Content Useful Bits & Links
The End

 

DOWNLOAD & NOTES

Firstly, here is the download link to the example code as promised.

 

EXAMPLE CODE DOWNLOAD

Click here to download all the example source code, I have released it under the MIT license, so feel free to build on top of it or use it in your own project.

 

QUICK NOTES

If you spot a bug, please feel free to comment below. I try to answer questions too, but it is one person versus the entire world… If you need answers urgently, please check out my list of websites to get help with programming.

 

 

JAVASCRIPT FETCH CONTENT

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

 

THE HTML

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

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

 

THE JAVASCRIPT

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

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.

 

 

DUMMY HTML

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

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

 

USEFUL 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()

 

 

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!

Leave a Comment

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