Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select an element and its siblings

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?

like image 388
Gary Avatar asked Apr 22 '12 15:04

Gary


People also ask

What is a sibling element?

Sibling. A sibling is an element that shares the same parent with another element.

Is used to select all the siblings of an 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.

Which of the following selectors selects siblings?

The ("element ~ siblings") selector selects sibling elements that appear after the specified "element". Note: Both of the specified elements must share the same parent.


2 Answers

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();
like image 165
drinchev Avatar answered Sep 22 '22 06:09

drinchev


for prev siblings and self:

$(this).prev().andSelf().toggle();

for all siblings and self:

$(this).parent().children().toggle();
like image 27
jurijcz Avatar answered Sep 18 '22 06:09

jurijcz