Reputation: 92983
Say I have a <dl>
with all the <dd>
s hidden. Clicking on a <dt>
toggles the <dd>
s that follow it using the following code:
$(this).nextUntil('dt').toggle();
http://jsfiddle.net/mblase75/FZQj7/
Now, I want to automatically hide the <dd>
s following the other <dt>
s, so I try to grab the siblings with this code:
$(this).nextUntil('dt').toggle()
.siblings().filter('dd').hide();
http://jsfiddle.net/mblase75/FZQj7/1/
But nothing happens, because each <dd>
I've already selected with .nextUntil
is a sibling to each other. As a result, they're all hidden and nothing gets shown.
There must be a compact way to tell jQuery to select all the siblings EXCEPT those I've already selected, but I can't see it. Ideas?
Upvotes: 5
Views: 1345
Reputation: 95062
You could do it from the parent:
$('dt').on('click',function() {
$(this).nextUntil('dt').toggle().siblings("dt").not(this).nextUntil('dt').hide();
});
Upvotes: 2
Reputation: 11096
Here's something a little simpler than these others:
$('dt').on('click',function() {
$(this).siblings('dd').hide();
$(this).nextUntil('dt').show();
});
Upvotes: 0
Reputation: 14785
A simple solution is to apply a class to the elements you show. On each click, you can hide the elements with this class before showing the desired set.
$('dt').on('click',function() {
$('.visibledd').hide().removeClass('visibledd');
$(this)
.nextUntil('dt')
.toggle()
.addClass('visibledd');
});
Upvotes: 1
Reputation: 2832
How about this? Notice the use of the not
function, which you can read about here.
http://jsfiddle.net/lbstr/FZQj7/6/
$('dt').on('click',function() {
var $this = $(this),
$firstGroup = $this.nextUntil('dt');
$firstGroup.toggle();
$this.siblings('dd').not($firstGroup).hide();
});
Upvotes: 3