0

Trying to add a class ("show") to sequential childnodes in an array every 0.5 seconds so that I can taper the appearance of them. I'm getting the following error: Cannot read property 'classList' of undefined

I've tried to take the nodelist and convert it to an array and loop through it, with a setTimeout for every 0.5 seconds + i, but I can't get the class to add to the parent (I want to add the "show" class to the top level div that has the "testimonial-wrapper" class).

https://codepen.io/Finches/pen/RXeZvy

individualTestimonialsList = Array.from(testsEl.childNodes);

console.log('testimonials', individualTestimonialsList);

for (var i=0; i<individualTestimonialsList.length; i++) {
    setTimeout(function() {
        individualTestimonialsList[i].classList.add("show");
    }, 500 * i);
}

I've tried different ways of accessing the top level element at index i in the loop, but no success. Always get the "Cannot read property 'classList' of undefined" error despite seeing the "classList" property on them in the console.log I have in the code. Any help? Thanks.

Edit: Please note that the code is activated on scroll, so the height of the codepen viewing window needs to be small so it can get triggered.

Corey Bush
  • 183
  • 3
  • 16
  • 1
    It’s [`children`](https://developer.mozilla.org/en-US/docs/Web/API/ParentNode/children), not [`childNodes`](https://developer.mozilla.org/en-US/docs/Web/API/Node/childNodes). Things like Text nodes or Comment nodes don’t have a `classList`. – Sebastian Simon Aug 10 '19 at 23:50
  • 2
    Possible duplicate of [JavaScript closure inside loops – simple practical example](https://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example); just log `i` in `setTimeout`. Use `let` instead of `var`. – Sebastian Simon Aug 10 '19 at 23:54

0 Answers0