I want to use JavaScript to change the text of an element with Id ‘foo’.
The text it should change to should be taken from a file titled ‘bar.txt’ (can also be any other file format, as long as I get a string from the text inside.)
The text file and the HTML containing the script are in the same directory, and are visible to the client.
Searching for my problem on Google only led me to this link, which is for uploading a file to the website and isn’t what I need.
2
Answers
There are really two questions here:
I’ll assume you have a web server with these two files sitting next to one another:
my_page.html
→ the HTML file containing your page and scriptmy_text.txt
→ the text fileThis script on your HTML page will load the contents of the file:
And this will update the element:
Here is a complete script with some rudimentary error reporting on the page:
To get the text from
bar.txt
you need to make aGET
call using eitherXMLHttpRequest
orfetch
, whichever you prefer. Then you will need to set that text as theinnerHTML
property of the element you’re interested in.Note you will not be able to perform a
GET
call on your local machine without first spinning up a webserver.Example:
foo.html
:bar.txt
:What the browser renders: