views:

98

answers:

5

I have a standard list...

        <ul>
            <li><a href="#">blah 1</a></li>
            <li><a href="#">blah 2</a></li>
            <li><a href="#">blah 3</a></li>
            <li><a href="#">blah 4</a></li>
        </ul>

And my jQuery:

$('ul li a').live('click', function() {
    var parent = $(this).parent('li');
});

What I want to find out is the parent li's position in the list of the clicked link e.g. clicking on blah 3 would give me 2, blah 4 would give 3 etc.

Any ideas?

+1  A: 

The index method should do what you want.

scompt.com
+1  A: 
$(function() {
    $('ul li a').live('click', function() {
        var parent = $(this).parent('li');
        alert(parent.prevAll('li').size());
    });
});
kgiannakakis
Novel approach, but I imagine index() is faster.
Erik
+4  A: 
$('ul li a').live('click', function() {

    alert($(this).parent('li').index());

});

Will give you what you want, but keep in mind these are 0 based indexes -- ie the first line item is index 0, the last line item is 3.

jQuery index() method documentation

Erik
Thanks for the edit, Reigel
Erik
A: 

you can get the index of an element with jquery`s index

$('ul li a').live('click', function() 
{
    var index =  $(this).index();
});    
Alex Pacurar
A: 

No need to jQueryfy this :

$('ul li a').live('click', function() {
    var position = 0;
    var currentNode = this;
    var firstNode = currentNode.parentNode.firstChild;
    while(firstNode != currentNode) {
        position++;
        currentNode = currentNode.previousSibling;
    }
    alert(position);
});
Arkh
If there's no need to "jQueryfy", then why use _some_ jQuery (selector), but not take full advantage..?
peirix
Because the first poster already use jQuery to attach his event.But to get some position using $'s functions (which, if I'm not wrong, do more than selecting things) may be a little too much.jQueryfy the things which are not the same in some browsers (CSS selects, events handling etc.) but use simple, portable and fast javascript when possible.
Arkh