Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
69
rated 0 times [  76] [ 7]  / answers: 1 / hits: 33931  / 11 Years ago, tue, november 12, 2013, 12:00:00

This:


function myFunction()
{
document.write("sup");
}

called in html like:


<div id="myDiv">
<script>myFunction();</script>
</div>t

adds a string sup to the myDiv div element. Which is what I want, exactly. However, this:


function loadFile(uri)
{
var r = new XMLHttpRequest();
document.write("trying to open: " + uri);
r.open('GET', uri, true);
r.send(null);
r.onreadystatechange = function()
{
if (r.readyState == 4)
{
myFunction();
}
}
}

function myFunction()
{
document.write("sup");
}

called like this:


<div id="myDiv">
<script>loadFile("filename.txt");</script>
</div>

seems to be overwriting my whole html file. I.e. when I run it in Firefox it shows me only the string sup (that's the whole content of the page) but the page seems to be still loading (the loading icon of FF is still there animating, apparently infinitely).


First of all, this is going to be used only locally, offline, as a fast and handy way of presenting data (using html+js and web browser instead of plain text file). What I want is to load a local text file and then put some of its content as a part of the html page. The same as in my first example but with loading the text file first.


More From » html

 Answers
33

The issue is that when you run document.write after the document has loaded, it overwrites the entire document. If it is run before that, it does not overwrite it.



What you want to do is set the innerHtml of a specific element, something like:



document.getElementById(myDiv).innerHTML=Sup;

[#74325] Monday, November 11, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
vanessag

Total Points: 170
Total Questions: 98
Total Answers: 88

Location: El Salvador
Member since Sun, Sep 12, 2021
3 Years ago
;