Javascript read txt file and interpret as code

Asked

Viewed 257 times

3

I am working with the following code to import and display text files:

HTML

<input type='file' accept='text/plain' onchange='openFile(event)'>
<div id='output'>...</div>

Javascript:

var openFile = function (event) {
    var input = event.target;
    var reader = new FileReader();
    reader.onload = function () {
        var text = reader.result;
        var node = document.getElementById('output');
        node.innerText = text;
    };
    reader.readAsText(input.files[0]);
};

But I came up with the need that when importing, the content is interpreted as HTML, because the file contains lists in <ul><li>.

Would that be possible? If so, can you explain to me what I should change?

1 answer

5


The .innerText will insert the content as plain text, ie HTML codes will be treated as text.

The .innerHTML will insert both text and render HTML codes if any.

Just exchange node.innerText = text; for node.innerHTML = text;.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.