I need to add a single class name to multiple objects using jQuery.
I'm aware of adding a class to multiple selectors like this:
$("#Div4 ,#Div5 ,#Div7 ,#Div8").addClass("something");
I tried the following code but it applies class only to the first object.
$(a[i].source, a[i].canvas, a[i].target).addClass("something");
In the above case, the classname something
is applied only to a[i].source
Thoughts?
Assuming that a[i].source
and etc. actually references a Node/Element, you can use .add()
to add them individually to a collection, i.e.:
$(a[i].source).add(a[i].canvas).add(a[i].target).addClass('something');
This can be unnecessarily verbose. You can simply construct an array and rely on implicit iteration in jQuery (credit to @Rory):
$([a[i].source, a[i].canvas, a[i].target]).addClass('something');
However, that's not really needed. What about just using native JS? Array.prototype.forEach()
and Element.classList
are very widely supported as of today:
ES6:
[a[i].source, a[i].canvas, a[i].target].forEach(el => el.classList.add('something'));
ES5 (if you need backwards compatibility with old browsers that doesn't support ES6 syntax):
[a[i].source, a[i].canvas, a[i].target].forEach(function(el) {
el.classList.add('something');
});