Published on

Fetch, Parse, and Display HTML Content with JavaScript


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 = "";

// Make a fetch request to the specified 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


    .catch(err => console.log('Failed to fetch the page:', err)); 

For example, if you've run this in, this is how it'll look like

Happy injecting HTML!