Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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>

??

like image 238
Latze Avatar asked Aug 10 '10 19:08

Latze


People also ask

Can I use JavaScript variables in HTML?

You cannot use js variables inside html. To add the content of the javascript variable to the html use innerHTML() or create any html tag, add the content of that variable to that created tag and append that tag to the body or any other existing tags in the html.

Can you use variables in HTML?

Use the <var> tag in HTML to add a variable. The HTML <var> tag is used to format text in a document. It can include a variable in a mathematical expression.

How do you pass a script variable in HTML?

You grab the element in Javascript using the assigned id value. var contentHolder = document. getElementById('content-holder'); To display the variable in HTML, assign the variable to the element in Javascript using the innerHTML property.

How do you store variables in HTML?

Answer: Use the concatenation operator (+) The simple and safest way to use the concatenation operator ( + ) to assign or store a bock of HTML code in a JavaScript variable. You should use the single-quotes while stingify the HTML code block, it would make easier to preserve the double-quotes in the actual HTML code.


3 Answers

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>
like image 116
jtbandes Avatar answered Oct 06 '22 20:10

jtbandes


You can do something like this:

<script>
  var str = 'hello there';
  document.getElementById('para').innerHTML = str;
</script>

where an element has the specified id:

<p id="para"></p>
like image 21
Sarfraz Avatar answered Oct 06 '22 20:10

Sarfraz


you simply cannot access javascript variable outside of the script tag, it is because,

  1. Html does not recognise any variable it just renders the supported HTML elements
  2. variables are used to store the temporary variables, that is for dynamic data, if you want something more dynamic then you can use PHP for that.
like image 36
Ibrahim Azhar Armar Avatar answered Oct 06 '22 19:10

Ibrahim Azhar Armar