Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
38
rated 0 times [  44] [ 6]  / answers: 1 / hits: 70478  / 14 Years ago, thu, april 1, 2010, 12:00:00

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!


More From » jquery

 Answers
16

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.


[#97182] Tuesday, March 30, 2010, 14 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
margaritakristinak

Total Points: 502
Total Questions: 127
Total Answers: 98

Location: England
Member since Mon, May 17, 2021
3 Years ago
;