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

287
Vistas
Adding a New Click Handler To An Existing Element?

I'm trying to add a new click handler to the #myDiv element below. I've tried something like this:

document.getElementById("myDiv").addEventListener("click", blah);

function blah() {
  console.log("test");
}

But I keep getting a console error stating, "Cannot read properties of null (reading 'addEventListener'). Is this because the other event listener isn't being called yet? Any help would be greatly appreciated. Thanks!

<!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 Respuestas
Responde la pregunta

0

Because document.getElementById("myDiv") is in the head tag which execute before the DOM loaded.

One solution is to add it in a script at the end of the body ( after the DOM loaded )

The second solution to make your script as module.

<!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 Denunciar
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