Home > database >  Javascript shows me TypeError saying my variable is undefined
Javascript shows me TypeError saying my variable is undefined

Time:05-10

Im trying to code a simple Javascript exercise where I have to place different text at different part of the page but it keeps throwing me a

TypeError:sal[0] is undefined

Here is the javascript code.

function sals(a,b,c,d,e,id)
{
    var sal = document.getElementsByClassName(id);
    sal[0].style.top=a;
    sal[0].style.left=b;
    sal[0].style.color=c;
    sal[0].style.fontsize=d;
    sal[0].style.zindex=e;
}

 sals('5%','50%','yellow','250px','20','GB');

What am I doing wrong?

For further reference, here is my HTML code aswell

<html>
<head>
<title>Hello</title>
<link rel="stylesheet" href="main.css">
</head>
<body>
    <h1 > Holla</h1>
    <script src="main.js"></script>
</body>
</html>

CodePudding user response:

Your JavaScript is running before the page (DOM) has fully loaded.

Your JS should really be in the head of your HTML

the simplest way to make sure the DOM is loaded before your JS runs, is to add 'defer' to the script tag thus;-

<head>
<title>Hello</title>
<link rel="stylesheet" href="main.css">
<script src="main.js" defer></script>
</head>
<body>   
<h1 > Holla</h1>
</body>
</html>
  • Related