views:

42

answers:

3

Hi Guys,

First post here so please be gentle :)

Ive tried searching all over the net and im not sure im searching by the right terms niether for its name. But what does the secondary options do in a jQuery selector? For example:

$('.results table', this.parent().prev())

The second lot of options on the .results table matches im not sure what this actually does? Is it similar to $('.results table').parent().prev() for example. Sorry ive just lifted this code as an example.

Appreciate the pointers as im just learning jQuery.

+2  A: 

It means to look for the selector somewhere "underneath" the elements referred to by the second parameter. It's like:

$('secondParameterSelector').find('firstParameterSelector') ...

With your example, it's like

this.parent().prev().find('.results table')

(that's assuming that this.parent().prev() is a jQuery object of course)

Pointy
+3  A: 

The second parameter is an optional context tha you can provide to the constrain the selector to search for matches only in the provided context. For example, say you're looping through the <tr> elements of a <table> and in each <tr> element you want to select the second <td> element. You could use the following

$('table tr').each(function() {
    $('td:eq(1)', this).doSomething(); // the function context, this, is the `<tr>`
                                       // element in each iteration
});

The selectors documentation is really very good and worth perusing through. In fact, the whole of the jQuery API documentation is good :)

Russ Cam
the jQuery docs are one of the main reasons to choose jQuery over other JS libraries
Erik
A: 

The second argument is the the context. For instance, if you wanted to echo the text of the first span element upon clicking any div:

$("div").click(function(){
  alert( $("span:first", this).text() );
});

The this in that example refers to which ever div was clicked. It's our context. This "context" can be a dom-element, document, or jQuery object.

Further reading: http://api.jquery.com/jQuery/

Jonathan Sampson