Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

jquery

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)?

like image 797
ChrisV Avatar asked Oct 21 '10 17:10

ChrisV


People also ask

What is the use of jQuery each () function?

each(), which is used to iterate, exclusively, over a jQuery object. The $. each() function can be used to iterate over any collection, whether it is an object or an array. In the case of an array, the callback is passed an array index and a corresponding array value each time.

How do you select element by id in jQuery?

The jQuery #id selector uses the id attribute of an HTML tag to find the specific element. An id should be unique within a page, so you should use the #id selector when you want to find a single, unique element.

What is the use of each () method?

The each() method specifies a function to run for each matched element. Tip: return false can be used to stop the loop early.

How can use multiple ID selectors in jQuery?

Select the ID's of different element and then use each() method to apply the CSS property on all selected ID's element. Then use css() method to set the background color to pink to all selected elements. Display the text which indicates the multiple ID selectors.


2 Answers

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).

like image 92
Pointy Avatar answered Nov 15 '22 00:11

Pointy


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() { ... });
like image 35
Nick Craver Avatar answered Nov 15 '22 01:11

Nick Craver