views:

28

answers:

1

I have a quick question about jQuery selectors.

Is doing this:

$('.class_el_1, .class_el_2').hide();

The same as just looping through each element using jQuery's .each function?

+4  A: 

It has the same effect of hiding them all, but it's not exactly the same internally, no. .each() takes a callback in which this can be used to do specific things to each element, so it does a bit more work. .hide() in a chain just sets display: none; on the elements (storing their previous value).

You can see how it works internally here, for your call with no parameters:

for ( var i = 0, l = this.length; i < l; i++ ) {
  var old = jQuery.data(this[i], "olddisplay");
  if ( !old && old !== "none" ) {
    jQuery.data( this[i], "olddisplay", jQuery.css( this[i], "display" ) );
  }
}

// Set the display of the elements in a second loop
// to avoid the constant reflow
for ( var j = 0, k = this.length; j < k; j++ ) {
  this[j].style.display = "none";
}

In the above this refers to the element set that $('.class_el_1, .class_el_2') matched, just using a for loop to literate over them.

Nick Craver
ah gotcha... but using a comma delimited list just allows you to modify more than one element?
dennismonsewicz
@dennismonsewicz - Yup, that's a [multiple selector](http://api.jquery.com/multiple-selector/), even just `.class` can get many elements, the comma separation lets you combine multiple selectors, and `.hide()` (or whatever really) will act on *all* of the matches...think CSS, they work exactly the same way.
Nick Craver
@Nick - Thanks for all of your help! This answered SO much!
dennismonsewicz
@dennismonsewicz - welcome :)
Nick Craver