André André - 8 days ago 5
Javascript Question

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?

Answer

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>

Comments