简体   繁体   中英

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?

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

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

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

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