This question has already been answered:

Hello. I have a script for the slider. I need to find the index of the element that contains the active class using jQuery. How can I do that? In my code, the error is $ slides [0] .hasClass is not a function

HTML

<div class="slider"> <div class="slide"> <img src="img/1.jpg" alt=""> </div> <div class="slide active"> <img src="img/2.jpg" alt=""> </div> <div class="slide"> <img src="img/3.jpg" alt=""> </div> </div> 

Js

 $(document).ready(function () { var $slides = $('.slider .slide'); console.log($slides[0].hasClass('active')); }); 

Reported as a duplicate by participants Crantisz , Air , 0xdb , Rostyslav Kuzmovych , Viktor Tomilov 2 Feb '18 at 11:50 .

A similar question was asked earlier and an answer has already been received. If the answers provided are not exhaustive, please ask a new question .

  • one
    console.log($slides.eq(0).hasClass('active')); - Igor

3 answers 3

Using index() :

 $slides.index('active') 

    jquery has an index method, just select the desired element and call the specified method:

     $('.slider .slide.active').index(); 

      https://api.jquery.com/index/

       $(document).ready(function () { var $slides = $('.slider .slide'); console.log($slides.index($('.slider .slide.active'))); }); 
       <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="slider"> <div class="slide"> <img src="img/1.jpg" alt=""> </div> <div class="slide active"> <img src="img/2.jpg" alt=""> </div> <div class="slide"> <img src="img/3.jpg" alt=""> </div> </div>