svenyonson
svenyonson

Reputation: 1909

Selecting child elements of a specific parent

I have an example of code (written by someone else) that works, but I cannot find any reference to this specific syntax to explain why it works:

var parent = $("#theParentDiv");
var child = $(".title", parent);

This will give me the child of the parent (there is only one), and excludes all other .title elements that do not descend from this parent.

How/why does this work?

Upvotes: 0

Views: 57

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1074555

The reference is here, in the documentation. The second parameter is called "context" by the docs.

It works because jQuery converts the call into a call to find.

This:

var child = $(".title", parent);

becomes this:

var child = $(parent).find(".title");

...which only looks for elements that match the selector if they're descendants of the parent.

In the 1.10.2 un-minified jQuery script, this happens on line 202, which looks like this:

return this.constructor( context ).find( selector );

Upvotes: 3

Related Questions