Home » Jquery » javascript – why i get the index of tag not index of class-Exceptionshub

javascript – why i get the index of tag not index of class-Exceptionshub

Posted by: admin February 24, 2020 Leave a comment

Questions:

when I’m use .index() in click function on element class i get the index of tag not the index of class.
here when i click element have class .mobapp-right i get (1 and 4) not (0 and 1).

$(document).ready(function(){
   $('.mobapp-right').click(function(){
        alert($(this).index());
    });
    $('.mobapp-left').click(function(){
        alert($(this).index());
    });
});
.mobapp-right{
    cursor: pointer;
}
.mobapp-left{
    cursor: pointer;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.2.3/jquery.min.js"></script>
    <ul > 
        <li>  </li>
        <li></li>
        <li></li>
        <li>  </li>
    </ul>
    <h1 class="mobapp-right"> right </h1>
    <h1 class="mobapp-left"> left </h1>
    <ul > 
        <li></li>
        <li></li>
        <li></li>
    </ul>
    <h1 class="mobapp-right"> right </h1>
    <h1 class="mobapp-left"> left </h1>
How to&Answer:

You can achieve it by using .index(element).

 $('.mobapp-right').click(function(){
     var index = $(".mobapp-right").index(this);
     alert("index is: " + index);
    });
    
$('.mobapp-left').click(function(){
     var index = $(".mobapp-left").index(this);
     alert("index is: " + index);
});
.mobapp-right{
    cursor: pointer;
}
.mobapp-left{
    cursor: pointer;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.2.3/jquery.min.js"></script>
    <ul > 
        <li>  </li>
        <li></li>
        <li></li>
        <li>  </li>
    </ul>
    <h1 class="mobapp-right"> right </h1>
    <h1 class="mobapp-left"> left </h1>
    <ul > 
        <li></li>
        <li></li>
        <li></li>
    </ul>
    <h1 class="mobapp-right"> right </h1>
    <h1 class="mobapp-left"> left </h1>