Reputation: 101
I have two tables: one-row table standing above the multi-column table. I want to delete a column in a multi-column table by clicking the cell in a one-row table that is standing right above this column.
I am trying to do this by using this code:
$('.del-column').delegate('td', 'click', function() {
var index = this.cellIndex;
$(this).closest('.my-table').find('tr').each(function() {
this.removeChild(this.cells[ index ]);
});
});
Where .my-table is a multi-column table and .del-column is a one-column table. Any ideas why it does not work?
Here is a demo where I am trying to do this. And here is an explanation in the image.
Upvotes: 1
Views: 546
Reputation: 20740
$(this).closest('.my-table')
will not work, because .my-table
is not the ancestor of .del-column
. Try like below.
$('.del-column').on('click', 'td', function() {
var index = this.cellIndex;
$('.my-table').find('tr').each(function() {
this.removeChild(this.cells[ index ]);
});
$(this).remove();
});
Upvotes: 1
Reputation: 399
You could loop also through them like this and see if the index matches.
var upperTable = document.querySelector(".del-column");
var lowerRows = document.querySelectorAll(".my-table tr")
function removeCorresponding(event) {
upperIndex = event.target.cellIndex;
lowerRows.forEach(function(row) {
row.querySelectorAll("td").forEach(function(lowerCell, lowerIndex) {
if (upperIndex === lowerIndex) {
lowerCell.remove();
event.target.remove()
}
});
});
}
upperTable.querySelectorAll("td").forEach(function(cell, upperIndex) {
cell.addEventListener("click", removeCorresponding);
});
https://jsfiddle.net/rt9oju8b/1/
Upvotes: 1
Reputation: 337590
Firstly, delegate()
is deprecated. You need to use on()
instead.
To fix your actual issue, you need to fix the DOM traversal logic you use, as the .my-table
is not a parent of the clicked cell, but a child of a sibling of the parent div
. You can also use the :nth-child()
selector to get the td
elements in the column without having to loop. Try this
$('.del-column').on('click', '.del', function() {
var index = this.cellIndex + 1;
$(this).closest('div').siblings('div.canvas').find('table tr td:nth-child(' + index + ')').remove();
$(this).remove();
});
Also note that the HTML for this is very over-complicated. It can be achieved much more simply by using a single table. It will also help the layout stay aligned too.
Upvotes: 1