Ben
Ben

Reputation: 3025

jQuery $(this) syntax question

Is this a valid selector? If not, what's the correct way?

$($(this)+' childElement')....

Upvotes: 1

Views: 2401

Answers (4)

Justin Ethier
Justin Ethier

Reputation: 134157

This may be what you are looking for:

$('childElement', $(this))

Basically it will search for childElement within the context of the current element, this.


For more information, see the documentation for the jQuery() function. In particular, the following excerpt explains the second argument and how it is equivalent to using find:

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. For example, if within a callback function we wish to do a search for an element, we can restrict that search:

$('div.foo').click(function() {
  $('span', this).addClass('bar');
});

Since we've restricted the span selector to the context of this, only spans within the clicked element will get the additional class.

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

Upvotes: 7

kieran
kieran

Reputation: 2312

Or...

$(this).children('.element');

Upvotes: 0

Aliostad
Aliostad

Reputation: 81660

Use

 $(this).find("childrenSelector")

Upvotes: 4

Matt
Matt

Reputation: 3848

$(this).find('childrenSelector');

Upvotes: 4

Related Questions