-2

I am trying to add some javascript to my HTML document. In my example I would like to display the square of 2 in text with HTML. The result should be calculated using a js script. For example, consider this:

In my header:

<script type="text/javascript">
  var square = 2*2
</script>

In my body:

<p>The square of 2 is <span id="square">.</span></p>

What do I have to add to make this work?

Tom
  • 705
  • 2
  • 9
  • 13
  • 5
    On the other hand it's ok to ask beginner questions, but on the other hand this is covered in literally almost every JavaScript tutorial there is. – JJJ Apr 12 '13 at 12:57
  • @Juhana, first one is on the one hand :p joke aside, my opinion is that SO is not made for answering this kind of questions. – Bojan Kovacevic Apr 12 '13 at 13:00
  • 3
    @LittleBobbyTables Reputation! Fresh reputation! Come get it while it's hot! – JJJ Apr 12 '13 at 13:01
  • I typed up a page long answer that was 3 lines of code and 100 lines of explanation and then couldn't submit it because the question was closed :p – user229044 Apr 12 '13 at 13:11
  • 1
    @meagar You can still post it to one of the duplicates. – JJJ Apr 12 '13 at 13:13
  • Hahahah, I can't. The post-answer box is gone after refreshing the page and I'm not retyping it all. Might be possible to get my saved draft back but I'm not *that* interested in doing so. – user229044 Apr 12 '13 at 13:15
  • Yay, I apparently got retaliation-downvoted for just commenting in this thread. That hasn't happened in a while, thanks. – LittleBobbyTables - Au Revoir Apr 12 '13 at 13:33

2 Answers2

1

You need to set the innerHtml of the span to the value so it would be something like this:

<script type="text/javascript">
  var square = 2*2;
  document.getElementById('square').innerHTML = square;
</script>

But you will want to move this script to after where the span is written as the page is rendered procedurally and the span doesn't exist yet in the head. The other option is to wrap your code in a document.onload function like:

<script type="text/javascript">
  document.onload(function() {
      var square = 2*2;
      document.getElementById('square').innerHTML = square;
  });
</script>
Schleis
  • 41,516
  • 7
  • 68
  • 87
0

Try using the HTML Document Object Model, for example,

function changeText(){
 var ans = 2*2;
document.getElementById("square").innerHTML = ans;
}

Then, attach this javascript to an event such as

<body onload="changeText()">
KernelPanik
  • 8,169
  • 1
  • 16
  • 14