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

161
Visualizações
Must I always make sure with some function that the DOM will be completed for then executing the JS code?

I am learning about events in JavaScript, following the official documentation, where the first example is: HTML:

<button>Change color</button>

JS:

const btn = document.querySelector('button');
function random(number) {
return Math.floor(Math.random() * (number+1));
}
btn.onclick = function() {
console.log("Oprimieron el boton");
const rndCol = 'rgb(' + random(255) + ',' + random(255) + ',' + random(255) + ')';
document.body.style.backgroundColor = rndCol; 

The previous code does not work unless you use an event for when the DOM is loaded completely, the error is: DOM.HTML: 11 Uncaught Typeerror: Cannot Set Properties of Null (setting 'onclick') (my JS file is called Dom). Investigating I found that it may be because the DOM has not been generated when the script declares and uses the constant obtained by the Dom button. To fix the error use: window.onload = function () { } Inside her I put the example code, the error is solved, the question is, must I always make sure with some function that the DOM will be completed for then executing the JS code?

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