Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community!

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Iterating through an array of divs

Im trying to create a carousel that iterates through an array of divs and implements a style change after 2 seconds.

The console is throwing an error

Uncaught TypeError: Cannot read property 'display' of undefined

it will also throw this error when i flip the display and style property, but then the console reads

Uncaught TypeError: Cannot read property 'style' of undefined

<div class="inside">
          <div class="inner1">
          <h1>This is Inner div 1</h1>
        </div>
          <div class="inner2">
            <h1>This is Inner div2</h1>
            </div>
          <div class="inner3">
              <h1>This is Inner div3</h1>
            </div>
          <div class="inner4">
              <h1>This is Inner div4</h1>
            </div>
        </div>
 var slideShow=document.querySelectorAll('.inside');

for (var i=0; i<slideShow.length; i++){
  setTimeout(function(){
    slideShow[i].display.style='inline-block';
  }, 2000)
}
Kristopher Van Sant
Kristopher Van Sant
Courses Plus Student 18,830 Points

Hey there, I adjusted the markdown around your code to make it more readable.

2 Answers

Kristopher Van Sant
PLUS
Kristopher Van Sant
Courses Plus Student 18,830 Points

I'm not sure really how to go about a carousel the way your trying to do it, hopefully someone else will jump in. But in regards to the undefined, I've been playing with the code you've posted and your array is actually empty, you're getting these undefined errors because slideShow has not been defined. I placed a console.log(slideShow); and console.log(slideShow.length) and viewed it in the console and it shows the length to be 0. So it sounds like nothing is being assigned to the slideShow variable at the beginning. That's just what I've gathered so far.

Seth Kroger
Seth Kroger
56,409 Points

Forget my previous answer, I know I ran into some issue with the NodeList/Array difference before, but you should be able to use slideShow[i]. The real issue is you have display.style backwards. It should be style.display.

Another issue you're going to have is your selector will only select the outer div, not any of the children div's. I think the query you're looking for is var slideShow = document.querySelector('.inside').childNodes();