helloworld1234 helloworld1234 - 1 month ago 5
HTML Question

How can remove next cell in table using JavaScript?

I have the code below:



function colspan(){
var x = document.getElementById("Cell2");
x.setAttribute("colspan", 2);
x.next().remove();
}

<table border="1">
<tr>
<td id="Cell1">Cell 1</td>
<td id="Cell2">Cell 2</td>
<td id="Cell3">Cell 3</td>
</tr>
<tr>
<td id="Cell4">Cell 4</td>
<td id="Cell5">Cell 5</td>
<td id="Cell6">Cell 6</td>
</tr>
<tr>
<td id="Cell7">Cell 7</td>
<td id="Cell8">Cell 8</td>
<td id="Cell9">Cell 9</td>
</tr>
</table>

<input type="button" onclick="colspan();" value="Change"/>





I would like to delete the next cell of the current cell I have called. When the Cell 2 is colspan, the Cell 3 should be removed, but I use
.next().remove()
is not working. Anyone can help?

Answer

This is something you could do.

function colspan() {
  var ele = document.getElementById("Cell2");
  ele.setAttribute("colspan", 2);
  if (ele.nextElementSibling) {
    ele.nextElementSibling.remove();
  }
}
<table border="1">
  <tr>
    <td id="Cell1">Cell 1</td>
    <td id="Cell2">Cell 2</td>
    <td id="Cell3">Cell 3</td>
  </tr>
  <tr>
    <td id="Cell4">Cell 4</td>
    <td id="Cell5">Cell 5</td>
    <td id="Cell6">Cell 6</td>
  </tr>
  <tr>
    <td id="Cell7">Cell 7</td>
    <td id="Cell8">Cell 8</td>
    <td id="Cell9">Cell 9</td>
  </tr>
</table>

<input type="button" onclick="colspan();" value="Change" />

Comments