00 Votes

jQuery: One Selector for multiple Elements with different Classes

Question by Compi | 2014-06-06 at 21:11

With jQuery, it is possible to use the selector $('#myid') to select the element with the ID "myid" or you can use $('.myclass') to select all elements with the class "myclass".

However, is it also possible to select multiple elements having no common class with only one selector? So, for example one selector for all elements with class "a" and all elements with class "b"?

I am asking this question because I do not want to add an additional class to all elements, I want to select (to have one class in common) and it would also be very awkward to treat all separate classes in my JavaScript individually although I want to handle them in the same way.

ReplyPositiveNegative
0Best Answer0 Votes

jQuery supports multiple selectors. The only thing, you have to do is to separate single selectors using a comma:

$(".a, .b").hide();

With this selector, you are selecting all elements with the class a or b and you hide them.

In this way, you can join arbitrary selectors with each other:

$(".a, #b, div").hide();

Similar to this is .add():

$(".a").add(".b").hide();

This first selects all elements with class "a", after that it adds all elements having assigned class "b".

A possible application would be:

$(".a").css("width","9px").add(".b").css("height","4px");

First, we select ".a" and set the CSS property "width" to "9px". After that, we are using .add(".b") to add all elements with class "b" to the amount of elements, we have already found. So, the change of the second CSS property applies to both elements ".a" and ".b" while the first change only affects the elements with ".a".
2014-06-07 at 21:15

ReplyPositive Negative
Reply

Related Topics

jQuery: Show and hide elements

Tutorial | 0 Comments

Important Note

Please note: The contributions published on askingbox.com are contributions of users and should not substitute professional advice. They are not verified by independents and do not necessarily reflect the opinion of askingbox.com. Learn more.

Participate

Ask your own question or write your own article on askingbox.com. That’s how it’s done.