var _sel1 = $('.red');
var _sel2 = $('.yellow');
How can I merge them into one, without using different selectors?
// I don't want to do it this way
var _sel3=$('.red,.yellow') or $('.red').add('.yellow');
The jQuery merge() method together merges the content of two arrays into the first array. This method returns the merged array. The merge() method forms an array containing the elements of both arrays. If we require the first array, we should copy it before calling the merge() method.
You can specify any number of selectors to combine into a single result. This multiple expression combinator is an efficient way to select disparate elements. The order of the DOM elements in the returned jQuery object may not be identical, as they will be in document order.
To select one element, then specify the css selector to $(), for example, $(“p”) selects all the p elements in the document and to select multiple elements matching one or more selectors then specify as $(“selector1, selector2, …”), for example, $(“p, div, span”) selects all the p, div and span elements in the document ...
Use add()
:
var _sel3 = _sel1.add(_sel2);
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