Question
When I click the table header row, I would like a generic function to get the id of the clicked <th> element, so I don't have to create a separate function for each header item.
I'm using jQuery, and have the following code:
HTML
<div id="title">
<table class="policies sortable">
<thead id="h-th">
<tr id="h-tr">
<th width="3%" id="h-client">Client</th>
<th width="7%" id="h-company-code">Company Code</th>
<th width="9%" id="h-unique-reference">Unique Reference</th>
<th width="8%" id="h-doc-date">Document Date</th>
<th width="8%" id="h-post-date">Posting Date</th>
<th width="7%" id="h-doc-type">Document Type</th>
<th width="5%" id="h-trip-id">Trip Id</th>
<th width="7%" id="h-ticket-no">Ticket Number</th>
<th width="6%" id="h-calc-tax">Calculate Tax</th>
<th width="15%" id="h-passenger-name">Passenger Name</th>
<th width="4%" id="h-error">Valid</th>
<th width="4%" id="h-processed">Processed</th>
<th width="4%" id="h-payment">Payment</th>
<th width="11%" id="h-updated">Updated</th>
</tr>
</thead>
</table>
</div>
JavaScript
$("#h-tr").click(function(item) {
console.log(item);
// get the id of the clicked <th>
});
if you include the th to the selector then you can access the id using $(this)
$("#h-tr th").click(function(item) {
console.log($(this).prop('id'));
});
You can call
querySelectorAll()on allthelements and use a loop to iterate andconsole.log()attributes once the EventListener is triggered by the element clicked.
document.querySelectorAll('th').forEach(element => {
element.addEventListener('click', () => {
console.log(element.getAttribute('id'))
})
})
th{cursor:pointer}
<div id="title">
<table class="policies sortable">
<thead id="h-th">
<tr id="h-tr">
<th width="3%" id="h-client">Client</th>
<th width="7%" id="h-company-code">Company Code</th>
<th width="9%" id="h-unique-reference">Unique Reference</th>
<th width="8%" id="h-doc-date">Document Date</th>
<th width="8%" id="h-post-date">Posting Date</th>
<th width="7%" id="h-doc-type">Document Type</th>
<th width="5%" id="h-trip-id">Trip Id</th>
<th width="7%" id="h-ticket-no">Ticket Number</th>
<th width="6%" id="h-calc-tax">Calculate Tax</th>
<th width="15%" id="h-passenger-name">Passenger Name</th>
<th width="4%" id="h-error">Valid</th>
<th width="4%" id="h-processed">Processed</th>
<th width="4%" id="h-payment">Payment</th>
<th width="11%" id="h-updated">Updated</th>
</tr>
</thead>
</table>
</div>