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

104
Vistas
Cannot figure out why my JS script will not trigger

I'm relatively new to JS so it might be blatantly obvious so I do apologize

I've written a small function that generates a random hexcode to apply against a html class, but it just won't initialize.

<!DOCTYPE html>
</head>
    

<body onload="get_random_color()">

    <p class="para">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas mollis.</p>
    <p class="para">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas mollis.</p>
    <p class="para">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas mollis.</p>
    <p class="para">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas mollis.</p>
    <p class="para">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas mollis.</p>

    <script language="javascript">
        var rand = document.getElementsByClassName("para");

        function get_random_color(){
            
            var letters ='0123456789ABCDEF'.split('');
            var color = '#';
            for (var i = 0; i < 6; i++) {
                color += letters[Math.round(Math.random() * 15  )];
            }
            return color;

            rand.style.backgroundColor = get_random_color();

        }


    </script>
    
</body>

Any insights or help would be greatly appreciated, thanks

J

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

You have many issue with the code.

  • Your body onload calls get_random_color, which correctly generates the color, but you then have a return which prevents it from being assigned to the style in the following line.
  • Variable rand is assigned not one element but a collection of elements. See the documentation of getElementsByClassName. Even if your return wasn't there, the collection does not have a style property. You have to set the style on each element using a for loop.
  • Inside the get_random_color function, the rand.style.backgroundColor = get_random_color(); calls itself - if return wasn't there, you'd get a stack overflow because the method would call itself over and over.
  • In general, always name your identifiers (like functions and variables) to fit their purpose. The variable rand is misnamed - it should be paragraphs or something like that.
about 4 years ago · Juan Pablo Isaza Denunciar

0

Gather up the paragraphs by class using querySelectorAll, iterate over them and apply a new color to each by calling the function.

const paras = document.querySelectorAll('.para');

paras.forEach(para => para.style.color = get_random_color());

function get_random_color() {
  var letters = '0123456789ABCDEF'.split('');
  var color = '#';
  for (var i = 0; i < 6; i++) {
    color += letters[Math.round(Math.random() * 15)];
  }
  return color;
}
<p class="para">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas mollis.</p>
<p class="para">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas mollis.</p>
<p class="para">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas mollis.</p>
<p class="para">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas mollis.</p>
<p class="para">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas mollis.</p>

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