Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

103
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda