10

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

5 Answers 5

9

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

Comments

6

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>

1 Comment

What difference does it make that the JavaScript code is in body?
2

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>

Comments

2

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>

1 Comment

well in the question he specifically mentioned it as 34 is the ecpected answer..... i have given him 2 solutions......i didn't want to assume anything......
2

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 :-)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.