Toggling an element and its siblings can be accomplished as:
$(this).toggle();
$(this).prev().toggle();
Combining them doesn't work:
$(this,$(this).prev()).toggle();
How can both be selected at the same time?
Sibling. A sibling is an element that shares the same parent with another element.
To select all sibling elements of an element, we will use siblings() method. The siblings() method is used to find all sibling elements of the selected element. The siblings are those having the same parent element in DOM Tree.
The ("element ~ siblings") selector selects sibling elements that appear after the specified "element". Note: Both of the specified elements must share the same parent.
For jQuery 1.8+, use .addBack()
:
$(this).prev().addBack().toggle();
For earlier jQuery versions, use the deprecated .andSelf()
call (see demo):
$(this).prev().andSelf().toggle();
for prev siblings and self:
$(this).prev().andSelf().toggle();
for all siblings and self:
$(this).parent().children().toggle();
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