Can I apply the same styling to two elements together in jQuery by grouping them like in CSS?

StackOverflow https://stackoverflow.com/questions/15937546

  •  03-04-2022
  •  | 
  •  

Question

This is simply for keeping code neater. In CSS I can group elements like this:

.element1,
.element2,
.element3,
.element4,
.element5,
.element6 {
 font-weight:bold;
}

is there anything similar in jQuery or would I have to set each separately.

$('.element1').css('font-weight', 'bold');
$('.element2').css('font-weight', 'bold');
$('.element3').css('font-weight', 'bold');
etc

I suppose I imagine something like

$('.element1', '.element2', etc).css('font-weight', 'bold);
Was it helpful?

Solution

Even more simple, you can use precisely the same selector in jQuery as you could in CSS:

$('.element1, .element2').css('font-weight', 'bold);

OTHER TIPS

The simple answer is yes, you can do that. But group your selectors using CSS syntax.

$('.element1, .element2, .element3').css('font-weight', 'bold');
$('.element1, .element2, etc').css('font-weight', 'bold');

JQuery multiple selectors.

Yes you can!

Except you want it like this: $('.element1,.element2').css('font-weight', 'bold);

Source: http://api.jquery.com/multiple-selector/

Use multiple selectors. Example:

$("div,span,p.myClass").css("border","3px solid red");
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top