ChrisV
ChrisV

Reputation: 9091

using jQuery .each() method on single-element id-selector

Explaining jQuery dialogs in the Nemikor Blog, Scott González uses the .each() method on an id selector:

$('#page-help').each(function() {
  var dialog = $('<div></div>')
    .load($(this).attr('href'))
    .dialog( ... );
  $(this).click(function() { ... });
});

Since an id selector can only return a single element, what is the purpose of using the .each() method? (which is normally for iterating over matched elements).

Is it just that there is no simpler way to execute a function for the 'page-help' element which provides access to $(this)?

Upvotes: 6

Views: 2127

Answers (5)

Aaron Anodide
Aaron Anodide

Reputation: 17186

I'd say it's a style choice. I actually like the selector way you show here because it attaches a scope to the primary participant in the logic in a (to me) self documenting way.

Upvotes: 1

Diodeus - James MacFarlane
Diodeus - James MacFarlane

Reputation: 114347

Why not just assign a variable?

var ph = $('#page-help')
var dialog = $('<div></div>')
ph.load($(this).attr('href'))
ph.dialog( ... );
$(ph).click(function() { ... });
});

Upvotes: 0

jcolebrand
jcolebrand

Reputation: 16025

It could also be done like this, but that wrapper gives you the fortunate use of $(this) instead of the following code:

var idPageHelp = $( $('#page-help')[0] );
var dialog = $('<div></div>')
  .load( idPageHelp.attr('href'))
  .dialog( ... );
idPageHelp.click(function() { ... });

Note I'm making an assumption that you want to focus on just the 0th element and I'm also focusing that you want to use idPageHelp as a jQuery object so I'm forcing it to be wrapped in a jQuery object.

Upvotes: 0

Nick Craver
Nick Craver

Reputation: 630379

He's using a .each() so this refers to the element and his variables are encapsulated in that callback function, though this would also work (but you'd have the variables left around):

var $this = $('#page-help'),
    dialog = $('<div></div>')
      .load($this.attr('href'))
      .dialog( ... );
$this.click(function() { ... });

Upvotes: 1

Pointy
Pointy

Reputation: 413702

It lets you mess with something without polluting the surrounding namespace. An alternative might be:

(function($this) {
  var dialog = $('<div></div>')
    .load($this.attr('href'))
    .dialog(...);
  $this.click(function() { ... });
})($('#page-help'));

I don't know which of the two is more disturbing. And I suppose I don't really know that that was the reason for doing it that way (that is, namespace tidiness).

Upvotes: 5

Related Questions