Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to 'output' a JavaScript variable into an HTML div

I have a JavaScript variable and I want the HTML div to output 7.

I know it's simple, but I can't seem to get my head around this.

<!DOCTYPE html>
<html>
    <head>
        <script type="text/javascript">

            var ball = 3+4;
        </script>
    </head>

    <body>
        <div>Have 7 output here</div>
    </body>
</html>
like image 659
user3011959 Avatar asked Nov 20 '13 07:11

user3011959


4 Answers

Give a specific id to the div like:

<div id="data"></div>

Now use the following JavaScript code.

<script type="text/javascript">
    var ball = 3+4;
    document.getElementById("data").innerHTML=ball;
</script>
like image 57
jaydeep namera Avatar answered Oct 28 '22 21:10

jaydeep namera


Fiddle

HTML

<html>
    <body>
        <div id="add_results_7"></div>
    </body>
</html>

JavaScript

<script>
    var ball = 3+4;
    document.getElementById('add_results_7').innerHTML=ball; // Gives you 7 as your answer
</script>
like image 28
malcolmX Avatar answered Oct 28 '22 22:10

malcolmX


Working code is here

Write your script in body.

Code

<!DOCTYPE html>
<html>
    <head>
    </head>

    <body>
        <div>Have 7 output here</div>

        <script type="text/javascript">
            var ball = 3+4;
            document.getElementsByTagName('div')[0].innerHTML = ball;
        </script>
    </body>
</html>
like image 34
Vipul Vaghasiya Avatar answered Oct 28 '22 22:10

Vipul Vaghasiya


Try this:

<head>
    <script type="text/javascript">
        var ball = 3+4;
        function op()
        {
            document.getElementById('division').innerHTML=ball;
        }
    </script>
</head>

<body onload="op();">

    <div id="division">Have 7 output here</div>
</body>
like image 22
Zword Avatar answered Oct 28 '22 21:10

Zword