forEach into for loop

Hello Friends,

I’m trying to convert this line of code forEach() into a For Loop (classic).
Hope you can help…
thanks.



function animatedForm(){
  var arrows = document.querySelectorAll('.fa-arrow-down');
  arrows.forEach(arrow => {
    arrow.addEventListener('click', () => {
      var input = arrow.previousElementSibling;
      // var parent = arrow.parentElement;
      // var nextForm = parent.nextElementSibling;
      console.log(input);
    });
  });

};

animatedForm();

So, forEach takes one by one the elements of the array and do something with them. If you know what is rapresenting each element of the array, you should be able to convert the code to a for loop without issues

So, let’s start with that, in the forEach callback, what is being used to reference the one array element considered in that moment?

Hi there,

Yes im trying to get it working with same functionality but im having trouble.
this is what i came up with but shows me an error.

function animatedForm(){
  var arrows = document.querySelectorAll('.fa-arrow-down');

    for( var i = 0; i < arrows.length; i++  ){
      arrows.addEventListener('click', function(){
        var input = arrows[i].previousElementSibling;
        console.log(input);
      });
    }

};

animatedForm();

Here is on the element

Here on the whole array. Maybe is that?

1 Like

I think i figured out see… for the forEach() with have this


function animatedForm(){
  var arrows = document.querySelectorAll('.fa-arrow-down');
  arrows.forEach(arrow => {
    arrow.addEventListener('click', () => {
      var input = arrow.previousElementSibling;
      // var parent = arrow.parentElement;
      // var nextForm = parent.nextElementSibling;
      console.log(input);
    });
  });

};

animatedForm();

so if i change it… for a for loop i get this

function animatedForm(){
  var arrows = document.querySelectorAll('.fa-arrow-down');

    for( var i = 0; i < arrows.length; i++  ){
      var arrow = arrows[i];
      arrow.addEventListener('click', function(){
        var input = arrow.previousElementSibling;
        console.log(input);
      });
    }

};

animatedForm();

the problem was that my arrows[i] i passed into a variable called var arrow = arrows[i];
and now i can addeventlistener to that variable on click, problably was because i was doing the click on the index[i] meaning the arrows[i].

now it works the same way.

yes we figured out at the same time… you where right… i miss passing the variable arrow element to the addEventListener.

1 Like