0

Just recently started to mess around with HTML and Javascript. For some reason a javascript variable isn't displaying in the HTML code when I run the HTML code.

HTML:

<td id="solider_cost"></td>

Javascipt:

var solider_cost = 100;
document.getElementById("solider_cost").innerHTML=solider_cost

When you run the HTML code, it displays this: Image. The variable is supposed to be in that cell.

So why isn't the variable displaying in the HTML? Let me know if you need to see more code.

Brian Fuller
  • 286
  • 1
  • 2
  • 10
  • 2
    Where’s the ` – Ry- Jun 04 '14 at 01:02
  • @false Oh, I feel silly, didn't even think about the script element. Forgot to put it at the bottom. Thanks. – Brian Fuller Jun 04 '14 at 01:03
  • I think your JS is eexecuted when thé DOM is not loaded so your TD does not exist. Where this js is executed ? – lpratlong Jun 04 '14 at 01:04
  • Without more details, there are so many things that *could* cause this problem. That doesn't mean *all* the code, just enough code to show it not working. – Jeremy J Starcher Jun 04 '14 at 01:04
  • Are you HTML and JavaScript in seprate locations? What is the debugger saying? Any errors being returned there? Can we see the full HTML and full JavaScript? Your code works fine for me. – mwilson Jun 04 '14 at 01:05

1 Answers1

0

The reason why it is not showing up is because your javascript code has been executed while your HTML code <td id="solider_cost"></td> hasn't exist yet.

So when you call the document.getElementById("solider_cost").innerHTML=solider_cost it could not find that element.

To accomplish your goal you can do the following options: I would recommend using the option 1 if that's all you need to do, otherwise, use Jquery.

  1. create a function and add it in the onload attribute of the HTML body

HTML

<html>
  <body onload="loadSomething()"> Content here.. 

  <script type="text/javascript">

     function loadSomething() {
         var solider_cost = 100;
         document.getElementById("solider_cost").innerHTML=solider_cost
     }

   </script> 
  </body>
</html>

2 . use Jquery

$(function() {

   var solider_cost = 100;

   document.getElementById("solider_cost").innerHTML=solider_cost

});

The code above will only be executed when the document is finished loading.

Hope that helps.

HandsomeG
  • 113
  • 9