views:

419

answers:

3

Is it possible to use jQuery to echo text in place of a script tag? More precisely, is there a way to accomplish

<script type="text/javascript">
    document.write("foo");
</script>

... without the use of document.write? I am not happy about using document.write after reading this.

I am aware that I could alternatively do this:

<span id="container"></span>
<script type="text/javascript">
    $("#container").text("foo");
</script>

However, I'm interested to see if there's a way to do it without using a container element, preferably using jQuery.

Thanks in advance!

+2  A: 

If you come up with a jQuery way of doing document.write(), it'll be bad for all the same reasons.

You are better off just using document.write() if that's what you need, or better yet, manipulating an existing element or appending a new element somewhere in the DOM--that's what jQuery is good at.

Michael Haren
+1 JQuery is a library on top of Javascript, it defers to JS for lots of common tasks (array and string management for example) as raw JS will always be faster!
Andy
A: 

jQuery's .append() is probably the closest method.

Kind Regards

--Andy

jAndy
A: 

Yes, and No. For what you want, no.

  1. Can you have it echo text to something without a true container, yes (see: DocumentFragment).

  2. Will it show up in your document... no. This is because it has not been told where it should be placed. The script tags in html do not maintain their position as a parameter directly so you could fudge around to find the last tag and put a TextNode there, however, this can be difficult and buggy.

What you can do instead is the general practice of do not modify the dom until an event such as "document.body.onLoad". This is a common practice, and generally is the way to go for ajax especially.

If none of this is suited for you, use the rare insertBefore(), jquery provides comparable support with .after and .before, on your script element with an id.

<script id="flail">
var flail=document.getElementById("flail");
flail.parentNode.insertBefore(document.createTextNode("TEST"),flail)
</script>

Note: This is generally a bad practice as it can create hanging loads, and encourages the html page to not be coherent without this output. However, like all things, there are cases for it's use.

bmeck