Question

I am trying to select all elements with the "findme" class, and from those get the selects that are nearby them. http://jsfiddle.net/R93md/1/

Specifically I have tried

$(".findme").parent().prev().first();

then once I have all selects I plan on doing a

.each(function (){doSomething(this);}) 

to each select. I am stuck getting the selects because it seems that I am never going down and retrieving the contents of the span.

Was it helpful?

Solution

$(".findme").closest("td").find("select").each(function() { 
    doSomething(this); 
});

OTHER TIPS

I think you should follow this:

$('.findme').each(function(){
    var el = $(this).closest('td').find('select');
    dosomething(el);
});

I would first grab the parent <td> element and then use find() like so

$('.findme').parents('td').find('select').each(function(){
    ...
});

http://jsfiddle.net/JYGK3/

Edit: In review of the other answers here, I've concluded that you probably should use closest() rather than parents(). If the table is nested, it could produce unwanted results.

http://jsfiddle.net/JYGK3/1

You can use .closest() to go up to the common <td> and then .find() to go down from there to find the neighboring <select>:

$(".findme").each(function() {
    var select = $(this).closest("td").find("select");
    // now do what you want to with the neighboring select object
    // here you have access to both this which is the findme object
    // and select which is the select object
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top