given the following
$("#identifier div:first, #idetifier2").fadeOut(300,function() {
// I need to reference just the '#identifier div:first' element
// however $(this) will grab both selectors
});
Is there a better way to go about this other than just calling $("#identifier div:first") again?
No, it'll call the function for each handle separately.
The comma in your selector is equivalent to saying:
$("#identifier div:first").fadeOut(300,function() {
// $(this) -> '#identifier div:first'
});
$("#idetifier2").fadeOut(300,function() {
// $(this) -> '#identifier2'
});
You can check by saying (untested):
$("#identifier div:first, #idetifier2").fadeOut(300,function() {
if($(this).is("#identifier div:first") {
// do something
}
});
However, if you want to do different things (as what seems from your post), its better to attach them separately.
What many people don't seem to realize in jQuery is that when there are multiple matched selectors, whatever functions are after the selector list will be called separately one at a time on each individual selector.
So $("#identifier div:first, #identifier2")
will separately match both:
$("#identifier div:first")
and
$("#identifier2")
And, will call the specified fadeOut
function and it's handler separately for each match. That means each handler will have it's own this
value set to the match the matched selector.
Internally inside of jQuery, there's a loop like this pseudo code that iterates through all the returned selector matches and calls the next function in the chain for each one:
for (var i = 0; i < matches.length; i++) {
jQuery["fadeOut"].call(matches[i], duration, easing, fn);
}
If you want separate code to be used for the two different matches, then it might be better to just use two separate jQuery statements:
$("#identifier div:first").fadeOut(300,function() {
// do stuff for #identifier div:first
});
$("#identifier2").fadeOut(300,function() {
// do stuff for #identifier2
});
If you have a lot of code in the block and it's mostly the same, then you can also branch within one block of common code:
$("#identifier div:first, #identifier2").fadeOut(300,function() {
if (this.id != "identifier2") {
// execute code that only applies to the #identifier match
}
// execute rest of common code
});
Just check about which ID you're currently processing in $(this)
if(this.id == "identifier"){ //your code goes here }