Home » Javascript code snippet » Read HTML Tags from URL as text file and insert them into an existing element – Javascript

Read HTML Tags from URL as text file and insert them into an existing element – Javascript

How to insert multiple HTML elements into an existing tag from Javascript code

You may get into a scenario where all the text or HTML tags need to be read from Notepad through Javascript and perform some action, such as pre-defined information or appending script tags like Google ads on page dynamically. This implementation proves exceptionally useful when you require consistent content across numerous pages. Furthermore, should you anticipate future alterations to this content, this approach allows for seamless updates without necessitating changes to each individual page where it has been incorporated, in such cases this method shows that it works really well.

The following example illustrates how to retrieve multiple HTML elements from a .txt file on the server/URL and add them into an existing <div> tag.

code snippet/ example:
<!DOCTYPE html>
<html>
<head>
    <title>Read text from URL</title>
</head>
<body>

	<!-- declare empty div with Id -->
    <div id="htmlTagsFromURL"></div>

    <script>
        // URL from which you want to fetch the text
        const url = 'https://www.codeindotnet.com/testdemo.txt';

        // Fetch the text content from the URL
        fetch(url)
            .then(response => response.text())
            .then(text => {
                // Select the div element where you want to insert the text
				const existingDiv = document.getElementById('htmlTagsFromURL');
				existingDiv.innerHTML = text;
            })
            .catch(error => {
                console.error('Error fetching the text:', error);
            });
    </script>

</body>
</html> 

output – screenshot
read html tag elments from url