ben
ben

Reputation: 29767

What does the 'this' word do in the following line of jQuery do?

What does the this part of the following line of jQuery do?

$('span:visible:first', this);

Upvotes: 0

Views: 145

Answers (3)

Guffa
Guffa

Reputation: 700152

As the this keyword is the current object, it depends on where that code is placed. If you specify a second parameter, it's used as context for the search, i.e. it will only look for elements within that context.

If you use that on it's own, this is the same as window so it's the same as $('span:visible:first', window).

If you use it inside an event handler, this is the element that the event was triggered on, so it will only seach for matches within that element.

Upvotes: 0

Pekka
Pekka

Reputation: 449385

It restricts the search specified in the first argument to the context of the this object.

Only children of this that match the specified requirements will be selected. Without the context, the search will apply to the whole document.

From the docs:

jQuery( selector, [ context ] )

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

Upvotes: 4

Nick Craver
Nick Craver

Reputation: 630339

Maybe turning it around would be the simplest explanation, it gets turned into this:

$(this).find('span:visible:first');

So it's using .find() to get all descendants of this (whatever that element is) that match your 'span:visible:first' selector.

Upvotes: 1

Related Questions