简体   繁体   中英

Deleting a user selected column in a html table using javascript ( no jQuery)

I have implement the following code to delete a column in a html table. I want to be able to implement this when the user selects a certain column rather than just the last column being deleted all the time - can anyone help ?

function deleteColumn(){

  var lastColumn = document.getElementById('Overall Result');
  var table = document.getElementById('tg-LTO9U');
  var rowCount = table.rows.length;
  for(var i=0;i<rowCount;i++){
     table.rows[i].deleteCell(table.rows[i].cells.length-2);
  }
}

Delete Column

I added a link to the table header to show how to pass an index to the function

 function closestByTagName(el, tagName) { while (el.tagName != tagName) { el = el.parentNode; if (!el) { return null; } } return el; } function delColumn(link) { var idx = link.getAttribute("data-idx"), table = closestByTagName(link, "TABLE"), rowCount = table.rows.length; for (var i = 0; i < rowCount; i++) { table.rows[i].deleteCell(idx); } return false; } window.onload = function() { var ths = document.querySelectorAll("th"); for (var i = 0; i < ths.length; i++) { ths[i].innerHTML += ' <sup><a href="#" data-idx="' + i + '" class="del" onclick="return delColumn(this)">X</a></sup>'; } } 
 sup { font-size:xx-small } .del { text-decoration:none } 
 <table> <thead> <tr> <th>A</th> <th>B</th> <th>C</th> <th>D</th> <th>E</th> </tr> </thead> <tbody> <tr> <td>One</td> <td>Two</td> <td>Three</td> <td>Four</td> <td>Five</td> </tr> <tr> <td>One</td> <td>Two</td> <td>Three</td> <td>Four</td> <td>Five</td> </tr> </tbody> </table> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM