0

I'm trying to figure out the reason why I can't use an index twice in a loop,
there should be something very simple that I'm missing.
the structure of the code is like this:

<p id="one">test</p>

<p class="two">a</p>
<p class="two">b</p>
<p class="two">c</p>

<script>
var one = document.getElementById("one");
var two = document.getElementsByClassName("two");
var i = 0;
while (i < two.length) {
  two[i].addEventListener("click", function() {two[i].innerHTML = one.innerHTML;});
  i++;
}
</script>

any suggestion will be appreciated =)

Enrico
  • 7
  • 1

3 Answers3

1

The problem is that when

function() {two[i].innerHTML = one.innerHTML;});

runs, the loop will have already completed, so i will be two.length. You need to either use a closure:

while (i < two.length) {
    (function(i) {
        two[i].addEventListener("click", function() {two[i].innerHTML = one.innerHTML;});
    )(i);
    i++;
}

or use a different type of loop and use let:

for(let i = 0; i < two.length; i++){
    two[i].addEventListener("click", function() {two[i].innerHTML = one.innerHTML;});
}
dave
  • 62,300
  • 5
  • 72
  • 93
0

The problem I see is that by the time the event handler is running (onclick), the value of i has been changed/lost.

If you replace this line: two[i].addEventListener("click", function() {two[i] = one.innerHTML;}); with two[i].addEventListener("click", function() {this.innerHTML = one.innerHTML;}); it should work correctly. "this" in the new version refers to the element that was clicked.

Chris Smith
  • 592
  • 3
  • 9
0

<p id="one">test</p>

<p class="two">a</p>
<p class="two">b</p>
<p class="two">c</p>

<script>
var one = document.getElementById("one");
var two = document.getElementsByClassName("two");
var i = 0;
while (i < two.length) {
    two[i].addEventListener("click", function () {
       this.innerHTML = one.innerHTML;
    });
    i++;
}
</script>
sidhik
  • 1
  • 1