title: swapping rows using a javascript
body: <p>I've a multiple number of rows which is generated by a for condition, with 2 icons up and down. On click of up the selected row should move one step up, and on click of down the selected row should move one step down</p>
  
  <pre><code>&lt;html&gt;
  &lt;head&gt;
  &lt;body&gt;
  &lt;form name="myForm"&gt;
  
   &lt;table id="mainTable" border="1" width="100%"&gt;
  
     &lt;script&gt;
       document.write('&lt;tr&gt;')
       document.write('&lt;td&gt;')
       document.write('row1')
       document.write('&lt;/td&gt;')
       document.write('&lt;/tr&gt;')
  
       document.write('&lt;tr&gt;')
       document.write('&lt;td&gt;')
       document.write('row2')
       document.write('&lt;/td&gt;')
       document.write('&lt;/tr&gt;')
       document.write('&lt;/table&gt;')
  
       document.write('&lt;table&gt;')
       document.write('&lt;tr&gt;')
       document.write('&lt;td&gt;')
       document.write('&lt;input type="button" value=" move UP " onClick="swapRowUp(getRowIndex(this))"&lt;/input&gt;')&gt;
       document.write('&lt;input type="button" value="move DOWN" onClick="swapRowDown(getRowIndex(this))"&lt;/input&gt;')&gt;
       document.write('&lt;/td&gt;')
       document.write('&lt;/tr&gt;')
       document.write('&lt;/table&gt;')
  &lt;/script&gt;
   &lt;/table&gt;
  
  &lt;/form&gt;
  &lt;/body&gt;
  &lt;/head&gt;
  &lt;/html&gt;
  &lt;script&gt;
  var mainTable = document.getElementById("mainTable"); 
  function getRowIndex(el)
  {
  while( (el = el.parentNode) &amp;&amp; el.nodeName.toLowerCase() !== 'tr' );
  
     if( el ) 
          alert(el.rowIndex);
          return el.rowIndex;
  }
  
  function swapRowUp(chosenRow) {
   if (chosenRow.rowIndex != 0) {
     moveRow(chosenRow, chosenRow.rowIndex-1); 
   }
  } 
  function swapRowDown(chosenRow) {
   if (chosenRow.rowIndex != mainTable.rows.length-1) {
     moveRow(chosenRow, chosenRow.rowIndex+1); 
   }
  } 
  
  function moveRow(targetRow, newIndex) {
  if (newIndex &gt; targetRow.rowIndex) {
     newIndex++; 
   }
  
   var mainTable = document.getElementById('mainTable'); 
  
   var theCopiedRow = mainTable.insertRow(newIndex); 
  
  
   for (var i=0; i&lt;targetRow.cells.length; i++) {
     var oldCell = targetRow.cells[i]; 
     var newCell = document.createElement("TD"); 
     newCell.innerHTML = oldCell.innerHTML; 
     theCopiedRow.appendChild(newCell); 
     copyChildNodeValues(targetRow.cells[i], newCell);
   } 
  //delete the old row 
   mainTable.deleteRow(targetRow.rowIndex); 
  } 
  
  
  function copyChildNodeValues(sourceNode, targetNode) {
   for (var i=0; i &lt; sourceNode.childNodes.length; i++) {
     try{
       targetNode.childNodes[i].value = sourceNode.childNodes[i].value;
     }
     catch(e){
  
     }
   }
  }
  
  &lt;/script&gt;
  </code></pre>
  
  <p>i'm unable to perform the swap operation, i get cellIndex as null</p>