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');
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With