helloworld1234
helloworld1234

Reputation: 327

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?

Upvotes: 1

Views: 150

Answers (3)

Sreekanth
Sreekanth

Reputation: 3130

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" />

Upvotes: 2

prasanth
prasanth

Reputation: 22490

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"/>

Upvotes: 0

antoni
antoni

Reputation: 5546

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

Upvotes: 0

Related Questions