Reputation: 129
So, I was trying to make HTML appear at the click of a button, but instead of inserting the HTML right where the script tag was, the entire page was overwritten with the code that was supposed to be generated. After experimenting, I found that something simple like
document.write("<p>" + "Hello!" + "</p>")
would simply insert it as it should. On the other hand, the code I was trying to do replaced the entire page.
Does anyone know how to fix this? Here is some example code.
function writeIFrame() {
document.write('<iframe width="500" height="300" src="https://www.youtube.com/embed/UJFdywQqovI" frameborder="0" allowfullscreen></iframe><p>Check out my YouTube channel <a href="https://www.youtube.com/channel/UCkqJM5HVjuvPA9H1VuFU5pQ">here</a> and subscribe!');
}
Upvotes: 1
Views: 3535
Reputation: 411
It's been two years since you asked this so, I suppose you will know the answer but I've seen that nobody answered correctly yet: document.write() will always overwrite all the document.
The best way to do what you were asking is to use the .innerHTML method with "+=" for example:
document.getElementById("test").innerHTML+= "Hi!";
And then you will have:
<p id="test"> Hi! </p>
Remark that +=
will always keep what is already written. If we want to replace what is inside the <p>
tag we must use only =
.
I know that you will for sure know this nowadays, but I hope to somebody can find this question and maybe get a good answer with this. :)
Upvotes: 0
Reputation: 1738
Depending on where your function is getting called.
If document.write
is called after html loading complete. It would overwrite the whole page. (Because appending it after closing html tags causes wrong syntax, thus make no sense doing so.)
Upvotes: 3