1

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?

prasanth
  • 21,342
  • 4
  • 27
  • 50
helloworld1234
  • 317
  • 1
  • 7
  • 19

3 Answers3

2

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" />
Sreekanth
  • 3,110
  • 9
  • 22
  • Yours one work better, since I work with JavaSricpt, it is better for me to work only one language rather than mix with JQuery, thanks for helping. – helloworld1234 Oct 25 '16 at 06:24
0

I think you are mixing jQuery and pure JS..

You should use nextSibling() & removeChild(element) on parent. have a look here: Remove element by id

Community
  • 1
  • 1
antoni
  • 4,295
  • 30
  • 39
0

The last remove() function was on jquery function. so use jquery library link and call the id with jquery type.

function colspan(){
     var x = document.getElementById("Cell2");
     x.setAttribute("colspan", 2);
     $('#Cell2').next().remove();
     }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<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"/>
prasanth
  • 21,342
  • 4
  • 27
  • 50