Create a jQuery instance from an array

4

I have the following array:

var elementos = [$("#elemento1"), $("#elemento2"), $("#elemento3")]

I need to create a function that "converts" this array into a jQuery instance, so I can use jQuery functions at all at the same time.

I've tried this:

var elementos = [$("#elemento1"), $("#elemento2"), $("#elemento3")];

$(elementos).hide();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><pid="elemento1">Elemento 1</p>
<p id="elemento2">Elemento 2</p>
<p id="elemento3">Elemento 3</p>

But I did not succeed, I know it would be best to use each. But is this possible?

    
asked by anonymous 26.06.2016 / 21:20

1 answer

4

You can do it in two ways, or itera the array and hide with jQuery ( example )

elementos.forEach(function($el){ $el.hide();});

or you use commas in the selector and you get a jQuery collection with 3 example )

var $els = $('#elemento1, #elemento2, #elemento3');
$els.hide();

Depending on how you are receiving these selectors, you can use whatever works best for you.

    
26.06.2016 / 21:22