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
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.
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.
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.
You can use $('li'). parent(). attr('id') to get the id of the parent element.
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);
});
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With