Reputation: 2593
I am running through my HTML file with jQuery in order to collect elements. Then, I want to execute a jQuery operation on each element that I found. This is what I have so far, but it doesn't work, as I do not know how to store the jQuery elements from the each method. Can someone help?
var foundElems = [];
$('#some-container .some-class').each( function(index) {
//filter $(this)
//store $(this)
foundElems.push($(this));
});
$('#some-container2 .some-class2').each( function(index) {
//filter $(this)
//store $(this)
foundElems.push($(this));
});
//do this again for many containers....
//then call some jQuery function on each element of that collection
foundElems.fadeOut('slow');
Upvotes: 2
Views: 204
Reputation: 1647
The simplest solution I could think of:
var array;
array = $.merge($(),$.find('#someContainer .someClass, #someContainer2 .someClass2'));
array.fadeOut(1000);
Upvotes: 0
Reputation: 94429
You can select multiple elements by separating them with a ,
.
$('#some-container .some-class, #some-container2 .some-class2').fadeOut('slow');
If you have to accommodate a bunch of these elements you could build an array with the selectors and pass that joined array into the jQuery function.
var arr = ["#some-container2 .some-class2","#some-container .some-class"];
$(arr.join(",")).fadeOut('slow');
Working Example http://jsfiddle.net/mBtKg/
Upvotes: 1
Reputation: 9167
Your jQuery seems fine, by the end of your .each statements you should have an array of elements. Your problem is that you can't call the .fadeOut on your array object.
You need to do this:
$.each(foundElems, function() {
$(this).fadeOut("slow");
});
Upvotes: 0
Reputation: 16188
Use $.merge()
var foundElems = $();
$('#some-container .some-class').each( function(index) {
//filter $(this)
//store $(this)
foundElems=$.merge(foundElems,$(this));
});
$('#some-container2 .some-class2').each( function(index) {
//filter $(this)
//store $(this)
foundElems=$.merge(foundElems,$(this));
});
//do this again for many containers....
//then call some jQuery function on each element of that collection
foundElems.fadeOut('slow');
You can also merge all your selector queries with the comma:
var foundElems = $();
$('#some-container .some-class,#some-container .some-class2,#some-container .some-class3').each( function(index) {
//filter $(this)
//store $(this)
foundElems=$.merge(foundElems,$(this));
});
//then call some jQuery function on each element of that collection
foundElems.fadeOut('slow');
Upvotes: 0