susmits susmits - 5 months ago 31
Javascript Question

Using jQuery to echo text

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">

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

I am aware that I could alternatively do this:

<span id="container"></span>
<script type="text/javascript">

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!


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");

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.