0

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?

2
  • jQuery(div#wallItem303.wallItem✉) should be jQuery('div#wallItem303.wallItem✉') - you're missing quotes. Commented May 7, 2011 at 12:43
  • @sime Error in the example, copied from firebug. Commented May 7, 2011 at 12:46

4 Answers 4

1

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/

Sign up to request clarification or add additional context in comments.

1 Comment

as i stated in the question. I know how to access the array in a loop. My question is if there's a more efficient way.
0

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');

Comments

0

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.

1 Comment

that would work, except the array exists of jQuery objects, not selector strings. I need to use this array.
0

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

1 Comment

as i stated in the question. I know how to access the array in a loop. My question is if there's a more efficient way.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.