Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

170
Views
Javascript shows me TypeError saying my variable is undefined

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>
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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>
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!