Latze Latze -4 years ago 114
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

-tags? Fx.

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

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

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

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


Answer Source

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();
<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>
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download