1

In this question, the following code is used -

var parent = $("#jcontent"); 
var button1 = $(".button1", parent) ;

to select a button of class button1 within the parent of id jcontent.

Why does this work? How does passing a jQuery object as a parameter to a jQuery selector tell it to select within that object? Can someone link to the docs which explain this function?

Community
  • 1
  • 1
Jasper Mogg
  • 924
  • 2
  • 8
  • 23
  • `$(".button1", parent)` is effectively the same thing as `parent.find('.button1')`. – Jasper Jun 20 '12 at 20:09
  • I swear you're following me :-p Keep it up haha! – Jasper Mogg Jun 20 '12 at 20:29
  • I like jQuery Mobile questions because answers for them can easily deviate away from standard JS answers. – Jasper Jun 20 '12 at 20:30
  • I like them because they're pretty much the only ones I know anything about :-D What do you mean though? The deviation makes them more interesting, or you want to rein them back in to standard JS? – Jasper Mogg Jun 20 '12 at 20:31

2 Answers2

6

It's the context parameter for the core method call.

The parameter is described as:

A DOM Element, Document, or jQuery to use as context

And then there's a section labelled "Selector Context," which starts with:

By default, selectors perform their searches within the DOM starting at the document root. However, an alternate context can be given for the search by using the optional second parameter to the $() function.

bdukes
  • 152,002
  • 23
  • 148
  • 175
5

The second parameter is the selector context: the DOM element, document, or jQuery object inside which the selector is matched. In the absence of this parameter, document root is assumed.

The following statement:

var button1 = $(".button1", parent); // parent = $("#jcontent")

is same as writing **:

var button1 = parent.find(".button1"); // parent = $("#jcontent")

and (in this case) produces results identical to this:

var button1 = $("#jcontent .button1");

** as mentioned here:

Internally, selector context is implemented with the .find() method, so $('span', this) is equivalent to $(this).find('span').

Salman A
  • 262,204
  • 82
  • 430
  • 521