Latze Latze - 3 months ago 9
Javascript Question

Can a JavaScript variable be used in plain HTML?

What I mean is, can a variable/array declared and initialized be used in HTML, outside the

<script>
-tags? Fx.

<script type="text/javascript">
var foo = array('placeholder1', 'placeholder2');
</script>

<body>
<p><!--access the variable here-->foo[0]</p>
</body>


How do you access the variable/array in this case? like this:

<p><script type="text/javascript">document.print(foo[0])</script></p>


??

Answer

Two ways to do this. This is the better one:

<script type="text/javascript">
// make sure to do this onLoad, for example jQuery's $()
var foo = array('placeholder1', 'placeholder2');
document.getElementById("fooHolder").innerHTML = foo.toString();
</script>
...
<p id="fooHolder"></p>

Or you could do it this way (which, as Marcel points out, doesn't work in XHTML and really shouldn't be used anyway):

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