Create an instance of jQuery from an array

Asked

Viewed 150 times

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 on all at once.

I tried that:

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

$(elementos).hide();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<p id="elemento1">Elemento 1</p>
<p id="elemento2">Elemento 2</p>
<p id="elemento3">Elemento 3</p>

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

1 answer

4


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

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

or use commas on the dial and receive a jQuery collection with 3 objects (example)

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

Depending on how you’re receiving these selectors you can use whatever suits you best.

  • As you can see, I tried to use $(elements). But when I try to hide them, it won’t.

  • @Salomãoneto you’re right. I was on the mobile and read wrong. I corrected and added examples.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.