Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to insert an element between the two elements dynamically?

Tags:

javascript

dom

I am using a table, in which there are buttons, on button click i want the new TR element to be inserted between the two TR or at the end of the TR... my code goes here

<table>
 <tbody>
   <tr>
     <td>
        <input type="submit" value="Add" onclick="addFunction()" />
     </td>
   </tr>
   <tr>
     <td>
        <input type="submit" value="Add" onclick="addFunction()" />
     </td>
   </tr>
   <tr>
     <td>
        <input type="submit" value="Add" onclick="addFunction()" />
     </td>
   </tr>
  </tbody>
 </table>

i want to insert new TR element next to the element which has triggered the event... NOTE: i am not using any javascript library, just plain javascript

like image 981
Harish Kurup Avatar asked Feb 27 '23 22:02

Harish Kurup


1 Answers

<table>
 <tbody>
   <tr>
     <td>
        <input type="submit" value="Add" onclick="addFunction(this)" />
     </td>
   </tr>
   <tr>
     <td>
        <input type="submit" value="Add" onclick="addFunction(this)" />
     </td>
   </tr>
   <tr>
     <td>
        <input type="submit" value="Add" onclick="addFunction(this)" />
     </td>
   </tr>
  </tbody>
 </table>

function addFunction(input)
{
  var newTr = document.createElement("tr");
  var curRow = input.parentNode.parentNode;
  curRow.parentNode.insertBefore(newTr, curRow.nextSibling);
}
like image 164
Matthew Flaschen Avatar answered Mar 09 '23 00:03

Matthew Flaschen