Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get an element position using jquery

I'd like to find an element position using JQuery. Not the X and Y position using .position .

For exemple

<ul>
    <li></li>
    <li></li>
    <li></li>
    <li></li>
    <li></li>
</ul>

And the js

//return the li pos
$('li').click(function(){...})

for exemple if I click the third li the function return the li pos witch is 2

I try something but it doesn't works

$('li').click(function(){
    for(var i = 0; i < $('li').length; i++){
        if($('li:eq('+i+')') == $(this)){
            alert(i);
            return true;
        }
    }
    alert('fail');
    return false;
})

And I always get fail

Thanks

like image 440
Ajouve Avatar asked May 20 '26 19:05

Ajouve


1 Answers

Use index() to get the position. It gives you zero-based index so you will get 0 for first element.

Live Demo

$('li').click(function(){    
    alert($(this).index())
});
like image 104
Adil Avatar answered May 22 '26 08:05

Adil



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!