Istiaque Ahmed Istiaque Ahmed - 1 year ago 31
jQuery Question

Explanation of two arguments for jQuery .each() method

In the following jQuery, the

method takes two arguments:
'ul li a'
. What do these two arguments mean?

var menu = $('.menu');
$('ul li a', menu).each(function() {
$(this).append('<span />');


<div class="menu">
<li><a href="#">Edit Profile</a></li>
<li><a href="#">Account Settings</a></li>
<li><a href="#">Appear Offline</a></li>
<li><a href="#">Logout</a></li>


The second parameter to the jQuery function is the context. This tells jQuery to only search for elements that are in that context

So for your example:

$('ul li a', menu).each(function() {
    $(this).append('<span />');

This will only search for anchors within li's within a ul, that are also located inside of menu.

This can be a very useful optimization since it can significantly cut down the amount of space jQuery has to search.


To possibly make this a bit clearer (as jfriend00 points out), your particular example, $('ul li a', menu), is equivalent to $('.menu ul li a')

The context parameter is explained here in the docs