Reputation: 3
ok, I have been through some basics but I'm not able to get this done. Problem is I don't want to specify id or class for any ul or li and if I click on a header included in the ul I want the li to be toggled (show/hide). How can I select the li under a header without specifying id and class???. Here is what I've tried :
<nav>
<ul>
<header>Menu 1</header>
<li>test</li>
<li>test</li>
<li>test</li>
<li>test</li>
<li>test</li>
<li>test</li>
<li>test</li>
</ul>
<ul>
<header>Menu 2</header>
<li>test</li>
<li>test</li>
<li>test</li>
<li>test</li>
<li>test</li>
<li>test</li>
<li>test</li>
</ul>
<ul>
<header>Menu 3</header>
<li>test</li>
<li>test</li>
<li>test</li>
<li>test</li>
<li>test</li>
<li>test</li>
<li>test</li>
</ul>
</nav>
<script type="text/javascript" src="js/jquery.js"></script>
<script>
$(function(){
$('ul li').hide();
$('ul header').css('cursor', 'pointer');
$('ul header').click(function(e) {
$(this).next().toggle();
});
});
</script>
Ok. This one just toggles the last child of ul but no all of them. Any help would be appreciated, Thanx.
Upvotes: 0
Views: 133
Reputation: 2832
If you use $.fn.toggle, it will alternate between two functions when you click. Then, you want to use the $.fn.siblings function to target all of the li
elements with the same parent. Here is a demo on jsfiddle.
$(function(){
$('ul li').hide();
$('ul header').css('cursor', 'pointer');
$('ul header').toggle(function(){
$(this).siblings('li').show();
},
function(){
$(this).siblings('li').hide();
});
});
EDIT: my recommendations were confusing and conflicting when separate, so I will group them all together and explain
1.) As Felix commented above, it is invalid HTML to have anything but li
as a direct decendant of ul
. So, you will need to change your markup to something like this:
<ul>
<li class="header">Menu 1</li>
<li>test</li>
<li>test</li>
<li>test</li>
<li>test</li>
<li>test</li>
</ul>
2.) I would set the following rules in your CSS, so that you don't have to do them with jQuery:
nav ul li { display: none; }
nav ul .header { display: block; cursor: pointer; }
So, with these two recommendations in place, your jQuery would now look like this:
$(function(){
$('ul .header').toggle(function(){
$(this).siblings('li').show();
},
function(){
$(this).siblings('li').hide();
});
});
Putting all of my recommendations together in a new fiddle.
Upvotes: 1
Reputation: 318182
next() gets the immediate following sibling of each element in the set of matched elements. If a selector is provided, it retrieves the next sibling only if it matches that selector.
siblings() gets all the siblings of each element in the set of matched elements, optionally filtered by a selector.
$(function() {
$('ul li').hide();
$('ul header').css('cursor', 'pointer');
$('ul header').click(function(e) {
$(this).siblings('li').toggle();
});
});
Upvotes: 0