Home > Back-end >  javascript table column remove when click table
javascript table column remove when click table

Time:12-13

It can be awkward because English is not my first language.

I have a task to write pure javascript code that deletes the clicked column when the table is clicked. Unfortunately I can't use jquery.

let cells = document.querySelectorAll("table td"); is the code I basically need to use.

window.onload = function () {
      function click(e) {
        let cells = document.querySelectorAll("table td");
        let index = e.target.cellIndex;
        cells.forEach((td, i) => {
          if (td.cellIndex === index) {
            td.parentElement.querySelectorAll("td")[index].remove();
          }
        })
      }
      
      // set onclick event for the head of each column
      document.querySelectorAll('tr > td').forEach(td => td.onclick = click)
    }

In my source, I delete all the columns to the right of where I clicked to see where the problem is.

Only the column of the clicked td should be deleted.

I don't know where the problem is or how to fix it.

CodePudding user response:

You can select the cells you want to remove via the nth-child selector, based on cellIndex. The below table demonstrates this:

function click(e) {
  let index = e.target.cellIndex;
  document.querySelectorAll(`tr td:nth-child(${index   1})`).forEach(cell => cell.remove());
}

// set onclick event for the head of each column
document.querySelectorAll('tr > td').forEach(td => td.onclick = click)
<table border="1">
  <tr><td>Column 1</td><td>Column 2</td><td>Column 3</td><td>Column 4</td><td>Column 5</td></tr>
  <tr><td>Column 1</td><td>Column 2</td><td>Column 3</td><td>Column 4</td><td>Column 5</td></tr>
  <tr><td>Column 1</td><td>Column 2</td><td>Column 3</td><td>Column 4</td><td>Column 5</td></tr>
  <tr><td>Column 1</td><td>Column 2</td><td>Column 3</td><td>Column 4</td><td>Column 5</td></tr>
  <tr><td>Column 1</td><td>Column 2</td><td>Column 3</td><td>Column 4</td><td>Column 5</td></tr>
</table>

CodePudding user response:

Collect all tr. Apply click eventListener to every single tr. The EventHandler collect all td's by column index. Then use remove() function.

document.querySelectorAll('tr').forEach((c) => {
  c.addEventListener('click', (e) => {
    document.querySelectorAll('tr td:nth-child('   (e.target.cellIndex   1)   ')')
     .forEach((td) => {
      td.remove();
    });
  })  
});
table {
  border: 1px solid #000;
}
<table>
  <tr><td>Col 1</td><td>Col 2</td><td>Col 3</td><td>Col 4</td></tr>
  <tr><td>Col 1</td><td>Col 2</td><td>Col 3</td><td>Col 4</td></tr>
  <tr><td>Col 1</td><td>Col 2</td><td>Col 3</td><td>Col 4</td></tr>
  <tr><td>Col 1</td><td>Col 2</td><td>Col 3</td><td>Col 4</td></tr>
  <tr><td>Col 1</td><td>Col 2</td><td>Col 3</td><td>Col 4</td></tr>
  <tr><td>Col 1</td><td>Col 2</td><td>Col 3</td><td>Col 4</td></tr>
</table>

  • Related