Question about the first() function


#1


First I want to thank CodeAcademy for giving these high quality lessons for absolutely free.

So I have no issues with completing the course, but I have a question about the first() function as its used in the code block. To my understanding, the next() function returns the next sister element of the calling object. Similarly, I assume the first() function returns the first sister element of the calling object in the code.

However, why is it necessary to write: nextSlide = $('.slide').first()

Rather than just: currentSlide.first() or equivalently $('.active-slide.').first()?

Referencing the active-slide class works when using the next() function, but it doesn't work when using the first() function. Why is that?


    $('.arrow-next').click(function(){
        var currentSlide = $('.active-slide');
        var nextSlide = currentSlide.next();
        
        if(nextSlide.length === 0){
            nextSlide = $('.slide').first();    
        }
        
        currentSlide.fadeOut(600).removeClass('active-slide');
        nextSlide.fadeIn(600).addClass('active-slide');
    });


#2

The jQuery object is a node list of elements all bearing the className 'slide'. The first() method returns the first node in this list.

currentSlide does not have a means to refer to the first sibling, and neither does active-slide. We need that node list.


#3

Ah, that makes sense. Thank you


#4

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.