javascript - document.write() works inline but not using jQuery's .html() - Stack Overflow

admin2025-04-18  0

If I have a document.write already in my dom as the page loads, it writes only where it's called to write. For example:

<div id="d1">
existing text <script>document.write('& doc written text');</script>
</div>
<div>footer</div>

Will render as <div id="d1">existing text & doc written text</div><div>footer</div>

However, if I were to use jQuery to update the html within div, like

$("#d1").html("another approach <script>document.write('wipes out the screen');</script>");

I end up simply with wipes out the screen b/c it essentially gets rid of everything in the document, vs. writing only where the inline script is. How can I .html() with a value containing document.write(), but have it behave the same as if it were in the dom to begin with (see first example). Thanks!

If I have a document.write already in my dom as the page loads, it writes only where it's called to write. For example:

<div id="d1">
existing text <script>document.write('& doc written text');</script>
</div>
<div>footer</div>

Will render as <div id="d1">existing text & doc written text</div><div>footer</div>

However, if I were to use jQuery to update the html within div, like

$("#d1").html("another approach <script>document.write('wipes out the screen');</script>");

I end up simply with wipes out the screen b/c it essentially gets rid of everything in the document, vs. writing only where the inline script is. How can I .html() with a value containing document.write(), but have it behave the same as if it were in the dom to begin with (see first example). Thanks!

Share Improve this question asked Mar 21, 2013 at 18:25 Ian DavisIan Davis 19.5k30 gold badges91 silver badges134 bronze badges 1
  • 1 You can't use document.write() after DOM is loaded, otherwise it will erase your entire document. Is there a reason you want to use it that way? – ulentini Commented Mar 21, 2013 at 18:28
Add a ment  | 

2 Answers 2

Reset to default 4

The html() function replaces the contents of an element. (See the API)

What you want is append().

If the page has fully been written, you can not use document.write(). There is nothing you can do to change how it behaves. You need to rethink what you are doing.

转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1744971129a277493.html

最新回复(0)