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

355
Vistas
Input elements having the same value with 'for' loop

I have just been experimenting with JavaScript and was trying this code.

var elements = document.getElementsByTagName("p");
var n = elements.length; // Should be: 10

for (var i = 0; i < n; i++) {
  elements[i].onclick = function () {
    console.log("This is element #" + i);
  };
}
<p>Element: #1</p>
<p>Element: #2</p>
<p>Element: #3</p>
<p>Element: #4</p>
<p>Element: #5</p>

However, when the code is run, something weird occurs. Basically, for example, if you click on element #1, it will say that you've clicked on element #5.


This is what I am curious to know:

  1. Why is this occurring?
  2. Is there a fix for it?
about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

change for var to let:

for (let i = 0; i < n; i++) {
  elements[i].onclick = function () {
    console.log("This is element #" + i);
  };
}
about 4 years ago · Juan Pablo Isaza Denunciar

0

You can use the code below to correct the issues.

var elements = document.getElementsByTagName("p");
var n = elements.length;

function makeHandler(num) {
     return function() {
         console.log("This is element #" + num);
     };
};

for (var i = 0; i < n; i++) {
    elements[i].onclick = makeHandler(i + 1);
}

Let's explain the code.


Basically, in this code, makeHandler is immediately executed each time we pass through the loop, each time receiving the then-current value of i + 1 and binding it to a scoped num variable.

The outer function (makeHandler) returns the inner function (anonymous function) (which also uses this scoped num variable) and the element’s onclick is set to that inner function.

This ensures that each onclick receives and uses the proper i value (by the scoped num variable).

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