9
votes

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>
5

5 Answers

7
votes

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>
6
votes

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>
2
votes

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>
2
votes

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>
2
votes

Try this:

<!DOCTYPE html>
<html>
  <head>
    <script type="text/javascript">
      onload = function () {
        var ball = 3 + 4;
        var div = document.getElementsByTagName("div")[0];
        div.innerHTML = ball;
      };
    </script>
  </head>
  <body>
    <div>Have 7 output here</div>
  </body>
</html>

onload is executed when the page is fully loaded, so the DIV is ready to be manipulated. getElementsByTagName("div") returns a list of all DIVs in the page, and we get the first one ([0]) since there is only one DIV in your code.

Finally, I guess innerHTML doesn't require any explanation :-)