-1

How can I read a file line by line in javascript and display each line in a different HTML tag? For example I want to store each line of the file in the a different <li> tag.

This is what I've tried so far, but it just displays the entire file as a whole. I want each line in a different tag:

 <embed src="C://whatever.txt">

Also tried code below but puts everything on the same line and not in different <li> tags but just in one:

    window.onload = function() {
    var ul = document.getElementsByTagName('ul')[0];

    function readTextfile() {
        var xhr = new XMLHttpRequest();

        xhr.onreadystatechange = function() {
            if (xhr.readyState === 4) {
                if (xhr.status == 200) {
                    showContents(xhr.responseText, xhr);
                }
            }
        }

        xhr.open('GET', "C://whatever.txt", true);
        xhr.send();
    }

    function showContents(responseText) {
        var li = document.createElement('li');
        var date = new Date();
        li.innerHTML = date + ': ' + responseText;
        ul.appendChild(li);
    }

    readTextfile();
Kann
  • 61
  • 7
  • Possible duplicate of [Javascript - read local text file](https://stackoverflow.com/questions/14446447/javascript-read-local-text-file) – evolutionxbox Jun 26 '17 at 16:41
  • 2
    Possible duplicate of [How to use Javascript to read local text file and read line by line?](https://stackoverflow.com/questions/23331546/how-to-use-javascript-to-read-local-text-file-and-read-line-by-line) – InvincibleM Jun 26 '17 at 16:42
  • @InvincibleM I'm asking how to display them in different HTML tags so it's not a duplicate – Kann Jun 26 '17 at 16:49
  • @styfle updated with what have done so far – Kann Jun 26 '17 at 17:00
  • `xhr.open('GET', "C://mockedapis.txt", true);` I doubt very much you're getting anything from that! – miken32 Jun 26 '17 at 17:13
  • @miken32 I am.... – Kann Jun 26 '17 at 17:15

1 Answers1

0

Change this line:

showContents(xhr.responseText, xhr);

To this code:

var lines = xhr.responseText.split('\n');
for (var i = 0; i < lines.length; i++) {
    showContents(lines[i]);
}

This will split the file into an array of lines. Then loop over each line and render inside an <li> element using your existing showContents function.

Additionally, I would change innerHTML to textContent so that you don't accidentally induce a XSS vulnerability.

styfle
  • 22,361
  • 27
  • 86
  • 128