Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get a parent element's index in jQuery

I'm having some trouble writing a jQuery function and could use a little help. Here's what I'd like to accomplish:

I have a ul element with 5 li children. Elsewhere on the page, I have a container div with 5 div children. When I click a link in the third li, I'd like to hide the other divs and show only the third one.

Currently every time I click a link in one of the li's, it returns the index of the li within all li's on the page, not within the containing ul.

Here's my code:

$('.products #productNav li a:not(.active)').live('click', function() {
    var index = $(this).parent().index('li');
    alert(index);
    $('.products #copy div').fadeOut(200,function() {
        $('.products #copy div').eq(index).fadeIn(200);
    });
});

Any ideas? Thanks much.
Marcus

like image 928
Marcus Avatar asked Jul 29 '10 14:07

Marcus


People also ask

How to get element index jQuery?

The index() is an inbuilt method in jQuery which is used to return the index of the a specified elements with respect to selector. Parameter: It accepts an optional parameter “element” which is used to get the position of the element. Return value: It returns an integer denoting the index of the specified element.

How to access parent in jQuery?

The parent() method returns the direct parent element of the selected element. The DOM tree: This method only traverse a single level up the DOM tree. To traverse all the way up to the document's root element (to return grandparents or other ancestors), use the parents() or the parentsUntil() method.

How to get nth child jQuery?

jQuery :nth-child() SelectorThe :nth-child(n) selector selects all elements that are the nth child, regardless of type, of their parent. Tip: Use the :nth-of-type() selector to select all elements that are the nth child, of a particular type, of their parent.

How can get ul id in jQuery?

You can use $('li'). parent(). attr('id') to get the id of the parent element.


1 Answers

Change .index('li') to .index() so it only gets the index number of its position relative to its siblings.

Here's a simplified example: http://jsfiddle.net/cWWLM/

$('.products #productNav li a:not(.active)').live('click', function() {

          // Get index of the parent <li> relative to its siblings
    var index = $(this).parent().index();
    alert(index);
    $('.products #copy div').fadeOut(200,function() {
        $('.products #copy div').eq(index).fadeIn(200);
    });
});
like image 161
user113716 Avatar answered Sep 24 '22 23:09

user113716