0

I am a beginner to javascript. I am currently learning it. HTML:

<!DOCTYPE html>
<html>
    <head>
        <title>Using Javascript</title>
        <meta http-equiv="author" content="@infinity">
        <link rel="stylesheet" type="text/css" href="css.css">
    </head>
    <body>
        <h1>Elderflower</h1>
        <script src="javascript.js"></script>
        <div id="content">
            <h2>Custom Signage</h2>
            <div id="cost">Cost: $5 per tile</div>
        </div>
    </body>
</html>

Javascript:

var number;
var costOne;
var totalCost;

number=5;
costOne=2;
totalCost=number*costOne;

var el=document.getElementById('cost');
el.textContent=totalCost;

Now I think that this should work, but its not working. The text of the <div id="cost"> remains same.

Please help.

codetalker
  • 576
  • 1
  • 6
  • 21

1 Answers1

2

Most likely you are trying to update the DOM even before it is loaded - you can make sure the javascript is executed after the DOM is loaded by keeping JS at the end of the body tag like below -

<!DOCTYPE html>
<html>
    <head>
        <title>Using Javascript</title>
        <link rel="stylesheet" type="text/css" href="css.css">
    </head>
    <body>
        <h1>Elderflower</h1>
        <div id="content">
            <h2>Custom Signage</h2>
            <div id="cost">Cost: $5 per tile</div>
        </div>
        <script>
                var number;
                var costOne;
                var totalCost;

                 number=5;
                 costOne=2;
                 totalCost=number*costOne;

                var el=document.getElementById('cost');
                el.textContent=totalCost;
        </scirpt>
    </body>
</html>

Start reading from here about Window load vs DOM load events

Community
  • 1
  • 1
Johnbabu Koppolu
  • 3,212
  • 2
  • 22
  • 34