In HTML/JavaScript code I dynamically generate a table with various elements. The first column consists of elements of type img to which I add a callback when a user clicks on one such image.
In the callback, how can I figure out the row of the image the user clicked on?
Do I have to use the element event.target.currentSrc (which contains the path to the image source) to figure that out? Or is there a better way to get the row of the image that has been clicked?
<div id="overlay">
<div id="modal-content">
<span class="close">Ă—</span>
<table id="myTable" class="aircraftTable"><thead>
<tr><th>Type</th><th>Cost</th><th>Range</th><th>Seats</th><th>Consumption</th></tr>
<tr><td><img src="static/img/A320neo.jpg" width="100"><br>A320 neo</td><td>97000000</td><td>5200</td><td>150</td><td>2.43</td></tr>
<tr><td><img src="static/img/B787-10.jpg" width="100"><br>B787-10</td><td>270000000</td><td>15000</td><td>246</td><td>2.37</td></tr>
</thead></table>
</div>
</div>
>Solution :
There is a rowIndex property you can use.
In this example I’ve attached one event listener to the table body element which catches events from its child elements (thanks to event delegation. When a table cell is clicked on the code finds the closest row element, and then grabs its index.
const tbody = document.querySelector('tbody');
tbody.addEventListener('click', handleClick);
function handleClick(e) {
if (e.target.closest('td')) {
const row = e.target.closest('tr');
console.log(row.rowIndex);
}
}
th, td { border: 1px solid black; padding: 0.5em; }
table { border-collapse: collapse; }
<table>
<tbody>
<tr><td>1</td><td>1.1</td></tr>
<tr><td>2</td><td>2.1</td></tr>
<tr><td>3</td><td>3.1</td></tr>
</tbody>
</table>