I need to know if it's possible to get the .html()
of a specific TH when it has no id or class set using jQuery selectors.
To illustrate my question:
TABLE
THEAD TR
TH1 TH2 TH3
TBODY TR
TD1 TD2 TD3
I set a $('table tbody tr td')
function that turns a cell into an input field on a double click, then back into text on blur, reflecting the change made to the cell via the input field.
I need to be able to know which column I am accessing. So if someone double clicks TD2 I want the input field name to contain TH2.
Please let me know how I can do this without setting id/class's for each TH or TD.
If the handler is on your <td>
element, then in your handler:
var th = $(this).closest('table').find('th').eq( this.cellIndex );
Table cells maintain their own index numbers, accessible through the cellIndex
property.
Table rows do the same thing via rowIndex
.
The jQuery methods are:
the closest()
[docs] method to get the <table>
the find()
[docs] method to find the nested <th>
elements
the eq()
[docs] method to reduce the <th>
elements down to the one at the same index as the <td>
A little further jQuery reduction could look like this:
var th = $(this).closest('table')[0].rows[0].cells[ this.cellIndex ];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With