I want to preview a text file inside a div tag which contains html code but the html part of the file is being rendered as html but not as text

I’m new to web design I wanted to make a web page which displays text of a “.txt” file. When I wrote any html code inside text file it is rendered instead if displaying the text

I wanted to preview all the contents in the text file. I want to display the html code in the file even though the code inside the text file contains html it should be displayed as a html code . I dont want it to be rendered as a html

function fileValidation(){
    var fileInput = document.getElementById('file');
    var filePath = fileInput.value;
    var allowedExtensions = /(.txt)$/i;
        alert('Please upload file having extensions .txt only.');
        fileInput.value = '';
        return false;
        //Image preview
        if (fileInput.files && fileInput.files[0]) {
            var reader = new FileReader();
            reader.onload = function(e) {
                document.getElementById('preview').innerHTML = e.target.result;
<!DOCTYPE html>
<html lang="en">
        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <link rel="stylesheet" href="css/styles.css" rel="nofollow noreferrer noopener">

        <div class="container">
            <div class="heading">


            <div class="preview" id="preview">
                 your file contents are displayed here ... 
            <div class="inp">

                    <form method="post" action=""  enctype = "multipart/form-data">
                        <input type="file" name="file_name" id="file" class="inputfile" onchange="return fileValidation()"/>
                        <label for="file">Select a file</label>

                    <div class="buttons">
                        <button class="encrypt" type="submit">
                        <button class="decrypt" type="submit">

    <script src="js/index.js"></script>


Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

You need to wrap the preview with <pre></pre> tag.
Set preview innerHtml to empty string and then append the value to it.

   reader.onload = function (e) {
        document.getElementById("preview").innerHTML = "";

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Notify of

Inline Feedbacks
View all comments
Would love your thoughts, please comment.x