Reputation: 21
I am using Javascript in an external file and it just won't seem to show up. The only syntax I can get to show up is: alert("Welcome user");. Nothing else will show. Below is the code I am working with.
<html>
<head>
<title>Hello World</title>
<link href="style.css" type="text/css" rel="stylesheet">
<script type="text/javascript" src="script.js"></script>
</head>
<body>
<script>
var x, y, z;
x = 5;
y = 6;
z = x*y;
document.getElementById("z").innerHTML = z;
</script>
<h2>Hello World</h2>
<p>Hello world!</p>
<p class="popular">Test.</p2>
</body>
</html>
The added tags are just to see if it would work in the HTML file itself. But no change.
var time = new Date().getHours();
if (time < 20) {
document.getElementById("demo").innerHTML = "have a good day!";
}
var x, y, z;
x = 5;
y = 6;
z = x*y;
document.getElementById("demo").innerHTML = z;
I hope someone can help me out with this as it is really bothering me!
Upvotes: 0
Views: 666
Reputation: 151
Change to this but you'll also need to move your scripts to the bottom of the code:
document.getElementsByClassName("popular")[0].innerHTML = z;
Upvotes: 0
Reputation: 5071
There are no elements matching the request for elementById()
. In addition your external file is executed as loaded thus being run prior to body element and all HTML elements in it being created. Thus you might prefer to insert scripts prior to closing body element by </body>
.
<html>
<head>
<title>Hello World</title>
<link href="style.css" type="text/css" rel="stylesheet">
</head>
<body>
<h2>Hello World</h2>
<p>Hello world!</p>
<p class="popular">Test.</p2>
<div id="z"></div>
<div id="demo"></div>
<script>
var x, y, z;
x = 5;
y = 6;
z = x*y;
document.getElementById("z").innerHTML = z;
</script>
<script type="text/javascript" src="script.js"></script>
</body>
</html>
Upvotes: 1
Reputation: 94
You don't have an element with an id="z"
or one with an id="demo"
Upvotes: 0