Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

153
Views
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
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!