简体   繁体   中英

What's the best way to select an element between one element and one of its ancestor using jQuery

I have a series of nested tables (that let's assume I can't change the structure of) and I need to select the outermost td.

Test HTML

<table>
    <tr>
        <td>
            <table class="relevanttable">
                <tr>
                    <td>one</td>
                    <td>two</td>
                    <td>
                        the important td
                        <table>
                            <tr>
                                <td>three - one</td>
                                <td>three - two <input id="targetinput" /></td>
                            </tr>
                        </table>
                    </td>
                </tr>
            </table>
        </td>
    </tr>
</table>

JS:

var relevant_field = $('#targetinput');
var target_table = relevant_field.closest('.relevanttable');
// I want something like this
var important_cell = last_selected.closest('.relevanttable > tr > td');

I think I can get this done with relevant_field.parentsUntil('.tableanswer', 'td') then figuring out which item is the furthest from it, but I'm wondering if there's a better way of attacking this and immediately selecting the exact td I'm interested in. This is a simple example, but there may be multiple tables nested within each other and the outermost table might not be the one I'm concerned with.

updates in response to the first few comments/answer(s):

$('#targetInput').parents('td').last()

isn't quite right since there's possibly more nesting than is shown in my example. That is table > table > table.relevanttable (this one isn't important, only closest) > table.relevanttable > table > table >...> td

Also, to provide some context, data is going to be written to the table based on user interaction. Since it's user interaction, there's no way to know in advance what's going to be important. There may be a table.relevanttable within a table.relevanttable, but only the closest one should be used. Think of of it like pasting data into Excel, except that some excel cells contain entire sheets. It's Excel meets Inception.

You can actually do something very similar to your example. You just need to take into consideration that browsers will add a tbody whether you add one or not.

$('#targetinput').closest('.relevanttable > tbody > tr > td');

http://jsfiddle.net/d7Zqf/1/

I was unable to find a reliable source which mentioned which browsers do and do not add the tbody . I would expect that all modern browsers do. I tested IE9 and current FF.

I'd personally suggest, though as yet untested:

$('#relevant_field').parents('td').last();

References:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM