0

Let's suppose that I have 3 files: ~/html/display.html, ~/data/text.txt, and ~/js/script.js. display.html has the following body:

<body>
  <p id="textblock">text</p>
  <script src="../js/script.js">
    loadTxt("../data/text.txt", "textblock")
  </script>
</body>

and text.txt contains the single line: text line

I want to know how I can make a function loadTxt, with the signature loadTxt(path, id) in script.js that takes the contents of path's text file and replaces the innerHTML of the paragraph with the given id with said contents.

I've tried using fetch and xhtml, but I'm having trouble navigating them.

Please also let me know if my syntax is wrong in my HTML. I'm not super used to working with scripts and HTML yet.

Unmitigated
  • 76,500
  • 11
  • 62
  • 80

1 Answers1

1

You can use fetch and get the response text.

function loadTxt(path, id){
    fetch(path).then(res => document.getElementById(id).innerHTML = res.text());
}
Unmitigated
  • 76,500
  • 11
  • 62
  • 80