How to display txt file contents in a html page?

Member

by lizzie , in category: HTML & CSS , a year ago

How to display txt file contents in a html page?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by dalton_moen , a year ago

@lizzie 

To display the contents of a text file on an HTML page, you can use JavaScript to fetch the contents of the file and then manipulate the DOM. Here's an example:


HTML:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
<!DOCTYPE html>
<html>
<head>
    <title>Display Text File</title>
    <script src="script.js"></script>
</head>
<body>
    <div id="fileContent"></div>
</body>
</html>


JavaScript (script.js):

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
window.addEventListener('DOMContentLoaded', (event) => {
    fetch('path/to/textfile.txt')
        .then(response => response.text())
        .then(data => {
            // Manipulate the DOM to display the text file contents
            const fileContentElement = document.getElementById('fileContent');
            fileContentElement.innerText = data;
        })
        .catch(error => console.log(error));
});


Make sure to replace "path/to/textfile.txt" with the actual path to your text file.


When the HTML page loads, the JavaScript code fetches the text file using the Fetch API. Once the contents of the file are retrieved, they are assigned to the innerText property of the fileContentElement which is a div element with the id "fileContent". This will display the contents of the text file on the webpage.