0

I'm using JQuery to append a script tag to a div, ex.:

$("#special_div").append("<script src="http://blablabla.com/id.php?id=0000"></script>");

and that script returns:

document.write("<object ....></object>");

but when I append it, all my HTML is gone and only that tag is written..

Can anyone tell me what's wrong?

Sarah
  • 1
  • 1

5 Answers5

1

Escape your quotes first of all:

$("#special_div")
  .append("<script src=\"http://blablabla.com/id.php?id=0000\"></script>");

Additionally document.write is fine depending on when it is called.

Edit: removed other text, other answerer about document.write enlightened me on this :D Thanks @Ivo

Jason Benson
  • 3,207
  • 17
  • 21
1

Here is the explanation:

Any document.write statement that runs after the page finishes loading will create a new page and overwrite all of the content of the current page

Don
  • 15,148
  • 9
  • 55
  • 91
0

What's wrong is that you're using document.write() — or at least the author of that script is using it. That's what document.write() does when it's called after the actual original document has been built by the browser. I suppose your code is in some jQuery initialization block:

$(function() {

  // your code somewhere in here ...

});

Thus it runs only when the browser has gotten the page all ready. But at that point, a new call to document.write() will be interpreted as meaning that you want to completely replace the current page with new stuff.

One thing to try would be to put an <iframe> in the document (not with document.write()!!) and then put the <script> tag inside that.

Pointy
  • 371,531
  • 55
  • 528
  • 584
0

The script that you load uses document.write, but you're loading the script after the page has already been loaded completely, therefore document.write will overwrite the contents of the page.

For more reasons against the use of document.write see:
Why is document.write considered a "bad practice"?

To fix it, you need to include the script in the HTML source itself.

Community
  • 1
  • 1
Ivo Wetzel
  • 44,463
  • 14
  • 89
  • 109
0

don't use document.write but appendChild to append the obejct tag

Martin Jespersen
  • 23,663
  • 6
  • 52
  • 66