Select an array of elements in jQuery

I need to wrap an array of elements in a jQuery object, as if they were selected so that I could call them various jQuery actions.

I am looking for a function like foobelow that takes an array of elements and returns a jQuery object with them in it.

var elements = [element1, element2, element3];

$(foo(elements)).click(function() {
    ...
});

Can someone shed some light on this?

Many thanks.

+3
source share
3 answers

Just do

$(elements).click( function(){ ... });

if your elements are actual DOM links

demo : http://jsfiddle.net/gaby/dVKEP/

+6
source

Use jQuery.each

Example:

$.each(elements, function(index, element) { 
    $(element).doStuff();
});
+3
source

Use each to iterate over both objects and arrays

var elements = ['element1', 'element1', 'elements3'];
$.each(elements, function(index, value) {
    alert(index + ': ' + value);
});

Check out the working example http://jsfiddle.net/LpZue/

+2
source

Source: https://habr.com/ru/post/1793498/


All Articles