dubbelj
dubbelj

Reputation: 1160

Way to access Array with jQuery objects

i've got an array like following

[jQuery('div#example1'), jQuery('div#example2'), jQuery('div#example3'), jQuery('div#etcetera')]

Goal

elementArray = [jQuery('div#example1'), jQuery('div#example2'), jQuery('div#example3'), jQuery('div#etcetera')];

$(elementArray).remove();

//or

$(elementArray).css('border', '1px solid red');

I want them all to get the same treatment, with some function. The only way i know to access the elements is to loop trough the array.

Can someone help me out with a more efficient way to go about this?

Upvotes: 0

Views: 2798

Answers (4)

Edgar Villegas Alvarado
Edgar Villegas Alvarado

Reputation: 18344

Here's the solution. The way you did is fine, however if you want to use a function, here you have:

$(elementArray).each(function(){
   $(this).css('border', '1px solid red');
   //Do whatever you want in this function
});

Hope this helps. Cheers

Upvotes: 0

Šime Vidas
Šime Vidas

Reputation: 185933

Here you go:

$.each(elementArray, function(i, v) {
    v.remove();
});

When using $.each, the function runs for every array element (which is referenced by v).

Live demo: http://jsfiddle.net/XyRZE/


Update: You could use map to replace each jQuery object in the array with the DOM element object that's contained within it.

$(elementArray).map(function(i, v) { return v[0]; }).remove();

Live demo: http://jsfiddle.net/XyRZE/1/

Upvotes: 1

redsquare
redsquare

Reputation: 78667

You can target multiple elements in a jquery selector.

See jQuery multiple selector api.

jQuery('#wallItem303, #wallItem303').remove();

N.B if you have an id do not prefix it with the nodeName in the selector.

Upvotes: 0

Oleg Grishko
Oleg Grishko

Reputation: 4281

Maybe you could select the items all together to one jQuery array

var myArray = $("div#wallItem303.wallItem, div#wallItem103.wallItem, div#wallItem323.wallItem");
myArray.css('border', '1px solid red');

Upvotes: 0

Related Questions