- Published on
Fetch, Parse, and Display HTML Content with JavaScript
- Authors
- Name
- Ashik Nesin
- @AshikNesin
There might be cases in which we might get HTML content from an URL and then inject it into the current webpage.
Here is how to do it:
// Define the URL from which the HTML content will be fetched (make sure to configure CORS)
const url = "https://nesinio-fetch-html.surge.sh";
// Make a fetch request to the specified URL.
fetch(url)
.then(response => response.text()) // Convert the loaded page to text.
.then(fetchedHTMLContent => {
const domParser = new DOMParser(); // Initialize the DOM parser.
// Use the DOM parser to convert the text to HTML elements.
const parsedHTML = domParser.parseFromString(fetchedHTMLContent, "text/html");
// It's possible to select part of the parsed HTML as in the regular DOM.
// For example:
const extractedHeading = parsedHTML.querySelector('body h1');
// And you can inject it into wherever you want
document.querySelector('body').appendChild(extractedHeading)
console.log(fetchedHTMLContent);
})
.catch(err => console.log('Failed to fetch the page:', err));
For example, if you've run this in example.com, this is how it'll look like
Happy injecting HTML!