简体   繁体   中英

Jquery - using each() to get position of a class element

I need to know the position of the "owl-item active", I know that the current position is 2. There are 3 photos in total.

<div style="transform: translate3d(-825px, 0px, 0px); transition: all 0.25s ease 0s; width: 48675px;" class="owl-stage">
    <div style="width: 825px; margin-right: 0px;" class="owl-item">
        <div class="gallery-item" style="background-image: url('/image/144/1.jpg');"></div>
    </div>
    <div style="width: 825px; margin-right: 0px;" class="owl-item active">
        <div class="gallery-item" style="background-image: url('/image/144/2.jpg');"></div>
    </div>
    <div style="width: 825px; margin-right: 0px;" class="owl-item">
        <div class="gallery-item" style="background-image: url('/image/144/3.jpg');"></div>
    </div>
</div>

How can I get the position of this "owl-item active" using a Jquery .each() ?

I've this code, but can't find a way to the code tell me that this "owl-item active" is in the position 2.

$('.owl-stage .owl-item').each(function( index, currentElement ) {
    console.log( index+1 );
    //console.log( $(currentElement).find('div.owl-item.active') ); 
});

Can someone give me a clue on how to do this?

You need to use hasClass method:

$('.owl-stage .owl-item').each(function( index, currentElement ) {
   if( $( this ).hasClass( 'active' ) ) { 
     console.log( index+1 );
   }
});

But you can use it even easier by just passing selector to index method:

console.log( $('.owl-stage .active').index( '.owl-item' ) + 1 );

 $(function() { console.log( '.active index is', $('.owl-stage .active').index( '.owl-item' ) + 1 ); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div style="transform: translate3d(-825px, 0px, 0px); transition: all 0.25s ease 0s; width: 48675px;" class="owl-stage"> <div style="width: 825px; margin-right: 0px;" class="owl-item"> <div class="gallery-item" style="background-image: url('/image/144/1.jpg');"></div> </div> <div style="width: 825px; margin-right: 0px;" class="owl-item active"> <div class="gallery-item" style="background-image: url('/image/144/2.jpg');"></div> </div> <div style="width: 825px; margin-right: 0px;" class="owl-item"> <div class="gallery-item" style="background-image: url('/image/144/3.jpg');"></div> </div> </div> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM