Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Same actions on same id, how to simplify?

I'm trying to do something like this, I feel this can be simplified, how can I do it?

$('#specificId').find('.class1').addClass('classA');
$('#specificId').find('.class2').addClass('classB');
$('#specificId').find('.class3').addClass('classC');

Can this be shortened to

$('#specificId').find('.class1, .class2, .class3').addClass('classA, classB, classC');
like image 978
thinkvantagedu Avatar asked Jul 12 '26 19:07

thinkvantagedu


1 Answers

You can't do that in a single operation. However you could do it in a loop over the properties of an object:

var obj = {
  class1: 'classA',
  class2: 'classB',
  class3: 'classC'
}

var $el = $('#specificId');
$.each(obj, function(key, value) {
  $el.find(`.${key}`).addClass(value);
});

It's not necessarily more simple, but it's certainly more extensible.

like image 98
Rory McCrossan Avatar answered Jul 15 '26 08:07

Rory McCrossan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!