0

I have a question which might sound silly. In the code below there are 2 console.log(i) statements. I want to know why does the second console.log(i) statement returns value of 2 and not 1 as the former on the first iteration (i.e. 1st statement i=n, 2nd: i=n+1). Shouldn't both be equal to 1 until the end of the loop?

function toggleWrapper(){
    var el1 = document.querySelectorAll('[class="tCell entryDesc"]');

    for (var i = 1; i < el1.length; i++) {
        console.log(i);
        el1[i].addEventListener('click', function(ev){
             console.log(i);
             var el2=document.querySelectorAll('[class="additionalInfoContainer"]');
             if (el2[i-2].clientHeight) {
                 el2[i-2].style.maxHeight = 0;
             }
             else{
                 el2[i-2].style.maxHeight = el2[i-2].scrollHeight +"px";
             }
        },
        false);
    }
}
Aditi Rawat
  • 784
  • 1
  • 12
  • 15
VTom
  • 31
  • 5
  • when the click happens, `i` will be `el1.length` for **all** `console.log(i);` ... also, arrays start at index 0, so you're missing the first one – Jaromanda X Jun 16 '18 at 08:32

2 Answers2

0

The problem is that the variable i, within each of your addEventListener() functions, is bound to the same variable outside of the function. simply change your for loop to :

for (let i = 1; i < el1.length; i++)

In the loop with let based index, each iteration through the loop will have a new value of i where each value is scoped inside the loop, so your code would work fine.

amrender singh
  • 7,949
  • 3
  • 22
  • 28
  • The idea is the following. I wish to design an interactive table of divs with an accordion effect. The main row entry contains the headers of the the information and on click of the description section (not the whole row) the more information section should roll-down. As you can see I get the entry desc.-n and the entire array of more info elements. I want upon clicking the main entry the corresponding more information field to open. – VTom Jun 17 '18 at 14:21
  • I am sorry to have bothered you guys. I solved it in another way. – VTom Jun 18 '18 at 09:12
  • I retrieved first both arrays of the elements concerned. Got the targeted element and compered indices. – VTom Jun 18 '18 at 09:15
  • @VTom Please mark answer accepted if it helped you :-) – amrender singh Jun 18 '18 at 09:56
0

i think is something in your code because if you try to make a for loop with two "console.log()" it doesn't do that

Gianmarco
  • 792
  • 2
  • 14
  • 38