Skip to content

Instantly share code, notes, and snippets.

@code-boxx
Created June 14, 2023 01:47
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Embed
What would you like to do?
Javascript Fetch Get HTML Content

JAVASCRIPT FETCH HTML CONTENT

https://code-boxx.com/get-html-content-javascript-fetch/

LICENSE

Copyright by Code Boxx

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

<!DOCTYPE html>
<html>
<head>
<title>JS Fetch</title>
<script>
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));
}
</script>
</head>
<body>
<div id="demo"></div>
<input type="button" value="Load Content" onclick="loadContent()">
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment