Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

172
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda