Alfred
Alfred

Reputation: 21386

How can I combine these jQuery statements?

I have a jQuery statement like this;

var current = $(this);
current.hide();
current.siblings('.ab').hide();
current.siblings('.cd').hide();

I want to change this into a single statement and I wrote;

$(current,current.siblings('.ab'),current.siblings('.cd')).hide();

But ab is not hiding. How can I combine the 3 hide() statements into one?

Upvotes: 5

Views: 177

Answers (5)

Frédéric Hamidi
Frédéric Hamidi

Reputation: 262919

You can use a multiple selector and addBack():

$(this).siblings(".ab, .cd").addBack().hide();

addBack() will add the original element back into the set, so you can get both the element and its relevant siblings in the same jQuery object.

Upvotes: 8

Rajaprabhu Aravindasamy
Rajaprabhu Aravindasamy

Reputation: 67207

Try to use .end(),

current.siblings(".ab, .cd").hide().end().hide();

or use .add() like below,

current.add(current.siblings(".ab, .cd")).hide();

Upvotes: 3

Milind Anantwar
Milind Anantwar

Reputation: 82231

You can use comma separated multiple selectors in .siblings()

 current.siblings('.cd,.ab').addBack().hide();

Working Demo

Upvotes: 1

Omar Sedki
Omar Sedki

Reputation: 608

try this:

   var current = $(this);

    current.hide().siblings('.ab').hide().end().siblings('.cd').hide();

Upvotes: 2

Irvin Dominin
Irvin Dominin

Reputation: 30993

You can use a multiple selector (comma separated) for the siblings function and than use addBack to include the first element.

Add the previous set of elements on the stack to the current set, optionally filtered by a selector.

Code:

current.siblings(".ab, .cd").addBack().hide();

Upvotes: 3

Related Questions