- JavaScript HTML DOM Document
- The HTML DOM Document Object
- Finding HTML Elements
- Changing HTML Elements
- Adding and Deleting Elements
- Adding Events Handlers
- Finding HTML Objects
- How to return HTML or build HTML using JavaScript?
- Returning HTML from a function
- Building HTML using DOM methods
- Example
- Building HML using DOM methods
- Building HTML using innerHTML
- Example
- Conclusion
- Get HTML Content With Javascript Fetch (Simple Example)
- TLDR – QUICK SLIDES
- TABLE OF CONTENTS
- JAVASCRIPT FETCH CONTENT
- PART 1) THE HTML
- PART 2) THE JAVASCRIPT
- PART 3) DUMMY HTML
- DOWNLOAD & NOTES
- SUPPORT
- EXAMPLE CODE DOWNLOAD
- EXTRA BITS & LINKS
- RETURN AS OTHER DATA TYPES?
- FETCHING HTML FROM ANOTHER SITE?
- COMPATIBILITY CHECKS
- LINKS & REFERENCES
- INFOGRAPHIC CHEAT SHEET
- THE END
- 2 thoughts on “Get HTML Content With Javascript Fetch (Simple Example)”
- How to Convert a String to HTML using JavaScript
- How to convert a String to HTML using JavaScript
JavaScript HTML DOM Document
The HTML DOM document object is the owner of all other objects in your web page.
The HTML DOM Document Object
The document object represents your web page.
If you want to access any element in an HTML page, you always start with accessing the document object.
Below are some examples of how you can use the document object to access and manipulate HTML.
Finding HTML Elements
Method | Description |
---|---|
document.getElementById(id) | Find an element by element id |
document.getElementsByTagName(name) | Find elements by tag name |
document.getElementsByClassName(name) | Find elements by class name |
Changing HTML Elements
Property | Description |
---|---|
element.innerHTML = new html content | Change the inner HTML of an element |
element.attribute = new value | Change the attribute value of an HTML element |
element.style.property = new style | Change the style of an HTML element |
Method | Description |
element.setAttribute(attribute, value) | Change the attribute value of an HTML element |
Adding and Deleting Elements
Method | Description |
---|---|
document.createElement(element) | Create an HTML element |
document.removeChild(element) | Remove an HTML element |
document.appendChild(element) | Add an HTML element |
document.replaceChild(new, old) | Replace an HTML element |
document.write(text) | Write into the HTML output stream |
Adding Events Handlers
Method | Description |
---|---|
document.getElementById(id).onclick = function()code> | Adding event handler code to an onclick event |
Finding HTML Objects
The first HTML DOM Level 1 (1998), defined 11 HTML objects, object collections, and properties. These are still valid in HTML5.
Later, in HTML DOM Level 3, more objects, collections, and properties were added.
Property | Description | DOM |
---|---|---|
document.anchors | Returns all elements that have a name attribute | 1 |
document.applets | Deprecated | 1 |
document.baseURI | Returns the absolute base URI of the document | 3 |
document.body | Returns the element | 1 |
document.cookie | Returns the document’s cookie | 1 |
document.doctype | Returns the document’s doctype | 3 |
document.documentElement | Returns the element | 3 |
document.documentMode | Returns the mode used by the browser | 3 |
document.documentURI | Returns the URI of the document | 3 |
document.domain | Returns the domain name of the document server | 1 |
document.domConfig | Obsolete. | 3 |
document.embeds | Returns all elements | 3 |
document.forms | Returns all elements | 1 |
document.head | Returns the element | 3 |
document.images | Returns all elements | 1 |
document.implementation | Returns the DOM implementation | 3 |
document.inputEncoding | Returns the document’s encoding (character set) | 3 |
document.lastModified | Returns the date and time the document was updated | 3 |
document.links | Returns all and elements that have a href attribute | 1 |
document.readyState | Returns the (loading) status of the document | 3 |
document.referrer | Returns the URI of the referrer (the linking document) | 1 |
document.scripts | Returns all elements | 3 |
document.strictErrorChecking | Returns if error checking is enforced | 3 |
document.title | Returns the element | 1 |
document.URL | Returns the complete URL of the document | 1 |
How to return HTML or build HTML using JavaScript?
When building web applications, there are often times when you need to dynamically generate HTML on the client-side. This can be done using JavaScript, and there are different ways to go about it. In this article, we’ll show you how to return HTML or build HTML using JavaScript.
Returning HTML from a function
One way to dynamically generate HTML is to return a string of HTML from a function. For example, let’s say we have a function that generates a list item −
We can then use this function to generate HTML −
The list variable now contains the following HTML −
Building HTML using DOM methods
Another way to dynamically generate HTML is to use DOM methods to build the HTML structure. This can be done by creating elements and then adding them to the DOM. For example, let’s say we want to create a list with the same items as before −
var list = document.createElement('ul'); var item1 = document.createElement('li'); item1.innerText = 'Item 1'; list.appendChild(item1); var item2 = document.createElement('li'); item2.innerText = 'Item 2'; list.appendChild(item2); var item3 = document.createElement('li'); item3.innerText = 'Item 3'; list.appendChild(item3);
The list variable now contains the following HTML −
Example
In the example below, we build HTML list using different DOM methods.
Building HML using DOM methods
We create a list by generating HTML elementsvar list = document.createElement('ul'); var item1 = document.createElement('li'); item1.innerText = 'JavaScript'; list.appendChild(item1); var item2 = document.createElement('li'); item2.innerText = 'Python'; list.appendChild(item2); var item3 = document.createElement('li'); item3.innerText = 'Rupy'; list.appendChild(item3); document.getElementById("result").appendChild(list)In the above program, we used the createElement method to create an unordered list and list items. The appendChild method is used to add the list items to the list.
Building HTML using innerHTML
Another way to build HTML is to use the innerHTML property. This can be done by creating an element and then setting its innerHTML property to a string of HTML. For example, let’s say we want to create a list with the same items as before −
The list variable now contains the following HTML −
Example
In the example below, we build an HTML list by assigning the list to the innerHTML.
In the above program, we create a list using the createElement method. The list items are added to the list using the innerHTML. To display the list we appended the element with using appendChild method.
Conclusion
In this tutorial, we’ve shown how to return HTML or build HTML using JavaScript. There are different ways to go about it, and the method you choose will depend on your needs.
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
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
No sweat. Just a to put the loaded contents into, and a to run the fetch content demo.
PART 2) THE JAVASCRIPT
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 .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.
- 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.
- 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.
- Captain Obvious, put the fetched contents in the .
- Lastly, handle any errors that may have happened. Optional, but highly recommended.
PART 3) DUMMY HTML
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.
SUPPORT
600+ free tutorials & projects on Code Boxx and still growing. I insist on not turning Code Boxx into a «paid scripts and courses» business, so every little bit of support helps.
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?
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
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)”
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.
How to Convert a String to HTML using JavaScript
JavaScript has many built-in APIs and methods that give you control over the HTML on the page.
One of the most useful ways to control the HTML is by converting a string to HTML.
From there, you can use the HTML to append to the DOM, or use it to replace the current page.
In this post, we’ll learn how to convert a string to HTML using JavaScript.
How to convert a String to HTML using JavaScript
To learn how to convert a string to HTML, first let’s define the string of HTML:
Convert a String to HTML
Learn how to convert a string to HTML using JavaScript.
`;Now, we can make use of the built-in DOMParser API to convert the string to HTML.
We already have the string of HTML, so we just need to pass in the type of content to parse, which is text/html :
Convert a String to HTML
Learn how to convert a string to HTML using JavaScript.
`; const parser = new DOMParser(); const html = parser.parseFromString(htmlString, 'text/html');From here, we can just take the html and get the body:
Convert a String to HTML
Learn how to convert a string to HTML using JavaScript.
`; const parser = new DOMParser(); const html = parser.parseFromString(htmlString, 'text/html'); const body = html.body; console.log(body);
Convert a String to HTML
Learn how to convert a string to HTML using JavaScript.