17

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>

??

7 Answers 7

24

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>
Sign up to request clarification or add additional context in comments.

4 Comments

document.write doesn't work in XHTML: w3.org/MarkUp/2004/xhtml-faq#docwrite
This is a good example of setting an HTML tag to contain a JavaScript variable's content. But it does not permit you to specify a JavaScript variable in HTML which automatically returns a JavaScript variable's content. The correct answer is that what is asked can not be done, but here is an alternative approach.
Why shouldn't document.write be used?
5

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>

Comments

3

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.

Comments

1

Unnecessarily verbose, but using standard DOM methods.

<script>
    window.onload = function(){
        // you do not need to initialize like this, but I like to
        var bar1 = new String('placeholder1');
        var bar2 = new String('placeholder2');
        var foo = new Array();

        // populate the Array with our Strings 
        foo.push(bar1);
        foo.push(bar2);

        // create an array containing all the p tags on the page 
        // (which is this case is only one, would be better to assign an id)
        pArray = document.getElementsByTagName('p');

        // create a text node in the document, this is the proper DOM method
        bar1TextNode = document.createTextNode(foo[0].toString());

        // append our new text node to the element in question
        pArray[0].appendChild(bar1TextNode);
    };
</script>

<body>
    <p></p>
</body>

Comments

0

That's the only direct way you'll access it elsewhere in your page. By opening another script tag and printing it.

You can also use methods such as innerHTML to put the value somewhere.

Comments

0

I don't think you can access the javascript from html but you can set the innerhtml of a dom object through javascript so you may want to go the other way around. First google search I found so I cant promise its good but it has a quick sample.

http://www.tizag.com/javascriptT/javascript-innerHTML.php

Comments

0

You can even you AngularJS expression.

<html>
     <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>

     <script>
        var app = angular.module('myApp', []);
        app.controller('myCtrl', function($scope) {
            $scope.framework= "AngularJS";
        });
    </script>

    <body>

        <div ng-app="myApp" ng-controller="myCtrl">
            <p>I want to use variables directly in HTML using: {{ framework }}</p>
        </div>

    </body>
</html>

The above code will print out "I want to use variables directly in HTML using: AngularJS".You can use braces to write AngularJS expression. For example: {{ expression }}.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.