2

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 class="GB"> Holla</h1>
    <script src="main.js"></script>
</body>
</html>
Spectric
  • 30,714
  • 6
  • 20
  • 43
Ash Crow
  • 23
  • 4
  • 1
    Does this answer your question? [Why does jQuery or a DOM method such as getElementById not find the element?](https://stackoverflow.com/questions/14028959/why-does-jquery-or-a-dom-method-such-as-getelementbyid-not-find-the-element) – Ivar May 09 '22 at 20:58
  • Move your script after the h1 tag – Martinez May 09 '22 at 21:04
  • 1
    As Martinez said, the script should be at the bottom of the body. Otherwise the script will load and try to find the `h1` element before it has loaded, causing it to give an `undefined` error. – htmlcat May 09 '22 at 21:13
  • Looks like your javascript is probably running before the DOM (HTML structure) is fully loaded, while moving the script after the tag is one possible solution you can also trigger your function on DOM loaded. In vanilla javascript you can use `document.addEventListener('DOMContentLoaded', function () { sal('5%','50%','yellow','250px','20','GB'); }, false);` – Philippe May 09 '22 at 21:14

1 Answers1

-2

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

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 class="GB"> Holla</h1>
</body>
</html>
Clint
  • 973
  • 7
  • 18