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

160
Vistas
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 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