Traversing table elements in jQuery
-
28-06-2021 - |
Domanda
I have a table structure as :
<table id = "cust-id">
<tr>
<td> 1</td>
<td id = "specific_id_re"><a href = "#">link tag</a></td>
</tr>
<tr>
<td> 2 </td>
<td id = "specific_id"> <a href = "#">link tag</a></td>
</tr>
</table>
I am trying to use jquery to access each of the table row columns that have an id and a link tag, but I am falling short. The best I have been doing is:
$('#cust-id').children().children().children() ; // to get access to the td elements ?
Any suggestions on what I should read or how I ought to approach this ?
Thanks Parijat Kalia
Soluzione
$('#cust-id td[id] a').each(function () {
var td = $(this).closest('td');
// do what you want
});
Altri suggerimenti
Try this
$("#cust-id tr:has(td[id] a)");
You can use the following selector $('#cust-id td[id]') this will return all td elements that has id attribute.
$('#cust-id td')
will gather all the td
elements under the element with #cust-id
. You can chain the selectors the same as in regular CSS.
If you want the row parents of a <td>
you can traverse back up from the <td>
using
$('#cust-id td').closest('tr')
Ah, you actually want just those <td>
that have <a>
and an id
, so...
$('#cust-id td[id] a').closest('td')
This selects all TD elements that are in the 2. column:
$( 'td:nth-child(2)', '#cust-id' )
This selects all TD elements that have an "id" attribute:
$( 'td[id]', '#cust-id' )
This selects all TD elements that contain a <a>
element:
$( 'td:has(a)', '#cust-id' )
So, if you combine those approaches, you can select those TD element that (1) have an "id" attribute, and (2) contain a <a>
element:
$( 'td[id]:has(a)', '#cust-id' )