How To Loop Through An Array Of Jquery Objects And .hide() Each Of Them
Solution 1:
The problems with your fiddle were as follows:
1) You hadn't included the jQuery library.
2) You hadn't closed the each
loop correctly (missing parenthesis).
3) You were missing the id
selector #
from "myButton".
Here's an updated, working fiddle.
Note, however, that you could simply do this:
$("#blue, #red, #green, #black, #purple, #orange").hide();
Or better, put all of those in a containing parent element, and simply hide that, or use $("#parent div").hide();
.
You can store the result of that selection in a single variable, rather than the 6 you currently have, as jQuery methods tend to operate on each element in the matched set without the need for a loop.
Solution 2:
is there a reason you want to do this trough an array of objects?
you could simplify it all by adding your selectors like this:
$('#blue, #red, #green, #black, #purple, #orange').hide();
Solution 3:
There are three problems:
- You run the code with the MooTools library instead of jQuery.
- You forgot
#
in the selector for the button. - You forgot a
);
at the end of the$.each
loop.
Solution 4:
$(myArray).each(function(index, element){
element.hide();
});
you may wanna try something like this!
var myArray = [$blue, $red, $green, $black, $purple, $orange];
$('#myButton').click(function() {
$(myArray).each(function(index, element) {
$(element).hide();
});
});
You can see it running here: http://jsfiddle.net/hd5qa/3/
Solution 5:
I prefer this way:
var elements = $("div");
var numOfElements = elemenets.length;
for(var i=0; i<numOfElements; i++) {
var element = elements.eq(i);
element.hide();
}
Post a Comment for "How To Loop Through An Array Of Jquery Objects And .hide() Each Of Them"