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

175
Vistas
forEach repeats functions

 document.querySelectorAll('.item').forEach(item => item.addEventListener (
    'click', function () {
        console.log('Hello World!')
    }
))
<div class="container">
  <article class="item">3</article>
  <article class="item">2</article>
  <article class="item">1</article>
</div>

As you can see I have container with three child element. I want to display 'Hello World!' when one of the article is pressed.

And when I press article that has 3 as content, console displays this:

forEach function is repeated 3 times

When I press second article:

forEach function is repeated 2 times

And when I press last article it displays only one 'Hello World!' in the console (how it must be). So it seems that this function is being repeated. And how to fix it?

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

I think your code is actually doing what you want but perhaps you're interpreting the number next to each console log incorrectly.

The number next to the console log entry indicates how many times that particular message has been logged within some interval of time.

If you change each of your listeners to also log data specific to each element, it will become more clear that each element's listener is only firing once.

<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <title>StackOverflow Example</title>
    </head>
    <body>
        <div class="container">
            <article class="item">3</article>
            <article class="item">2</article>
            <article class="item">1</article>
        </div>
        <script>
            window.onload = function () {
                document.querySelectorAll(".item").forEach((item, index) =>
                    item.addEventListener("click", function () {
                        console.log("Hello World!", index);
                    })
                );
            };
        </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