I have situation where my tables are dynamically generated with ids. Now i can generate two tables within same page and i need to manipulate these tables using their unknown ids. For example. Insert row button is available which when clicked should add row to selected table given there maybe more than one table on the page. How can i achieve this through javascript. This is what i have done so far:
please note the ids of the tables are dynamically generated so they are not known. I want to get id of table two whenever i click anywhere on the table.
The issue with my code is e.target.id gets id of any element clicked on the page and not necessarily the table. Its only if i click on the table head that the table id is gotten. But if i click inside the table the row id is chosen instead of the parent table id.
function RealClickHandler() {
document.addEventListener('click', function(e) {
var id = e.target.id;
}, false);
return id;
}
function insertrow() {
var tableid = RealClickHandler();
}
<button type="button" onclick="insertrow">Add row</button>
<table id="ABC">
<thead>
<tr>
<th>Header 1</th>
<th>Header 2</th>
</tr>
</thead>
<tbody>
<tr>
<td>Cell 1</td>
<td>Cell 2</td>
</tbody>
</table>
<table id="EFD">
<thead>
<tr>
<th>Header 1</th>
<th>Header 2</th>
</tr>
</thead>
<tbody>
<tr>
<td>Cell 1</td>
<td>Cell 2</td>
</tbody>
</table>
2
Answers
You code will not return the ID in the function RealClickHandler because that is not how event handling works. It will be the assigned click event handler itself that returns the id, not the function that assigns the event handler
You can use closest to get the table from a click on the table content
So my code needs the user to click the table before clicking the add button
You can add a
selected
class to a table when it’s selected and search for such a table that has such a class when the button is clicked. Of course, you will need to handle the case when no table was selected yet, or a table is selected (both in the case when no previous table was selected and when a previous table was selected). I’ve styled the selected table with lightgreen background to clarify the flow visually.