views:

1104

answers:

5

Hello, I'm trying to do make the following selection:

$(".program", row)

Where "row" is a jQuery object containing two table rows. One of the tr's has the class 'program". This selector doesn't seem to find it. However the following works:

$(".title", row)

where div.title is a descendant of tr.program.

If I use a jQuery object as a selector context, am I not able to match top-level elements of that jQuery object?

thanks,

-Morgan

A: 

You most certainly are able to match the top level elements. Could we see the source you're using? Your code should be working, so there's probably a problem in the HTML itself.

Salty
A: 

You're on the right path with descendants. Passing context to a selector searches for all descendants found in that context.

In your case, since the object is not a "parent containing two rows", but rather "a collection of rows", .program is not selectable. Since .title is an actual descendant in your collection, it is selectable.

Peter J
Cool. Thanks for confirming my observation. My object is the restult of $(someHTML).appendTo(aTable). Any suggestions about the best way to select one of those rows by class? I could iterate over the jquery object, but I'm hoping for someting a little prettier.
morgancodes
Iteration using jQuery's $.each function is not so ugly, if you want to retain your existing selector code.
Peter J
A: 

My understanding is that context needs to be root level i.e. a parent within which you want to make your selection.

EDIT: Having now done some reading, you should be able to match top level elements of the context (the default context is document).

Beardscratchers has a good article on using context with jQuery selectors. In general, you should attempt to pass an element id as the context for a jQuery wrapped set, as it is the most performant way of locating an element.

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

Russ Cam
+4  A: 

It looks like you're trying to select elements out of the ones you already have selected (residing in the jQuery object).

Context, as far as jQuery is concerned, is like specifying a parent - the context is a node somewhere ABOVE what you're looking for in the DOM tree. The context is where jQuery will look for the selector you've specified.

If I am correct about what you're attempting to do then this should work:

row.filter('.program');

// And then:
row.filter('.program').find('.title');
J-P
+1  A: 

Brandon Aaron has a must read article on jQuery context

slolife