Jasper Mogg
Jasper Mogg

Reputation: 924

Why does this jQuery selector work? What is it based on?

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?

Upvotes: 1

Views: 101

Answers (2)

Salman Arshad
Salman Arshad

Reputation: 272256

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

Upvotes: 5

bdukes
bdukes

Reputation: 156005

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.

Upvotes: 6

Related Questions