mpen
mpen

Reputation: 283143

How to simplify this jQuery expression?

$country.parent().parent().next().children('td').children('.province-select')

Basically I have some HTML that looks like this:

<table>
    <tr>
        <th>country</th>
        <td><select name="country"/></td>
    </tr>
    <tr>
        <th>province</th>
        <td><select class="province-select"/></td>
    </tr>
</table>

Once I've nabbed the country select, I need to find the next .province-select. Would be nice if it's little more robust to subtle HTML changes.

AFAIK next() only finds siblings, and closest() only traverses up the DOM tree.


I have a few of these all in the same table. That's why I'm using all this parent/next garbage. I don't want to use IDs because... well, then the script will only work on one specific country/province pair; I need it to run on all of them; thus I need to find the corresponding province field for the country field.

Upvotes: 0

Views: 129

Answers (5)

Antony Scott
Antony Scott

Reputation: 21996

if you can add IDs to your selects

$('#country') and $('#province-select') will get your elements, that's assuming your HTML isn't inside a repeater/list of some kind

Edit:
hmm, in that case have you tried the equivalent of GetElementsByName?

Upvotes: 1

redsquare
redsquare

Reputation: 78677

Below is ugly but will account for 'subtle' changes like adding extra tr's in between the two selects, it also accounts for multiple country/province pairs of select elements.

//cache closest tr so we can get its index and use it as the base for the next traversal
var $closesttr = $country.closest('tr');

//search the tbody  for the first instance of an element that has the class
// province-select and is after the tablerow that contains the current country

$closesttr.parent()
          .find('tr:gt(' + $closesttr.index() + ') .province-select:first');

Upvotes: 2

William
William

Reputation: 6428

I would probably go with:

$country.closest('table').find('.province-select');

Upvotes: 1

Felix Kling
Felix Kling

Reputation: 816910

For example:

$contry.closest('tr').next('tr').find('> td > .province-select')

Upvotes: 3

hookedonwinter
hookedonwinter

Reputation: 12666

You could try

$country.parents( 'tr' ).next().find('.province-select')

Upvotes: 2

Related Questions