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

286
Views
¿Agregar un nuevo controlador de clics a un elemento existente?

Estoy tratando de agregar un nuevo controlador de clics al elemento #myDiv a continuación. He intentado algo como esto:

 document.getElementById("myDiv").addEventListener("click", blah); function blah() { console.log("test"); }

Pero sigo recibiendo un error de consola que dice: "No se pueden leer las propiedades de nulo (leyendo 'addEventListener'). ¿Se debe a que todavía no se llama al otro detector de eventos? Cualquier ayuda sería muy apreciada. ¡Gracias!

 <!DOCTYPE html> <html lang="en"> <head> <style> [data-color="red"] { color: red; } [data-color="blue"] { color: blue; } [data-color="green"] { color: green; } [data-color="orange"] { color: orange; } [data-color="purple"] { color: purple; } </style> <script> window.myHandler = function () { console.log('Click!'); }; window.getRandomNumber = function (max) { return Math.floor(Math.random() * max) } var colors = ['red', 'blue', 'green', 'orange', 'purple']; window.changeHeadlineColor = function (croHeadline) { var random = getRandomNumber(5000); var randomString = random.toString(); setTimeout(() => { var colorKey = (randomString.length < 4) ? 0 : parseInt(randomString.charAt(0)); croHeadline.setAttribute('data-color', colors[colorKey]); changeHeadlineColor(croHeadline); }, random); }; </script> <script> //////////////////// /* YOUR CODE HERE */ //////////////////// </script> </head> <body> <div id="myDiv">OMG Click me!</div> <script> document.querySelector('#myDiv').addEventListener('click', myHandler); setTimeout(() => { myDiv.insertAdjacentHTML('beforebegin', '<h1 id="cro-headline" data-color="red">Cro Metrics</h1>'); var croHeadline = document.querySelector('#cro-headline'); changeHeadlineColor(croHeadline); }, getRandomNumber(5000)); </script> </body> </html>
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Porque document.getElementById("myDiv") está en la etiqueta head que se ejecuta antes de que se cargue el DOM .

Una solución es agregarlo en un script al final del cuerpo (después de cargar el DOM )

La segunda solución para hacer su script como módulo.

 <!DOCTYPE html> <html lang="en"> <head> <style> [data-color="red"] { color: red; } [data-color="blue"] { color: blue; } [data-color="green"] { color: green; } [data-color="orange"] { color: orange; } [data-color="purple"] { color: purple; } </style> <script> window.myHandler = function () { console.log('Click!'); }; window.getRandomNumber = function (max) { return Math.floor(Math.random() * max) } var colors = ['red', 'blue', 'green', 'orange', 'purple']; window.changeHeadlineColor = function (croHeadline) { var random = getRandomNumber(5000); var randomString = random.toString(); setTimeout(() => { var colorKey = (randomString.length < 4) ? 0 : parseInt(randomString.charAt(0)); croHeadline.setAttribute('data-color', colors[colorKey]); changeHeadlineColor(croHeadline); }, random); }; </script> <script type="module"> window.blah = function () { console.log('Click!'); }; document.querySelector('#myDiv').addEventListener('click', blah); </script> </head> <body> <div id="myDiv">OMG Click me!</div> <script> document.querySelector('#myDiv').addEventListener('click', myHandler); setTimeout(() => { myDiv.insertAdjacentHTML('beforebegin', '<h1 id="cro-headline" data-color="red">Cro Metrics</h1>'); var croHeadline = document.querySelector('#cro-headline'); changeHeadlineColor(croHeadline); }, getRandomNumber(5000)); </script> </body> </html>

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