faqts : Computers : Programming : Languages : JavaScript : DHTML

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

77 of 86 people (90%) answered Yes
Recently 9 of 10 people (90%) answered Yes

Entry

How can I swap two nodes in the document?
How can I swap two rows in a table?
How can I swap two nodes in the document?

Aug 14th, 2001 03:19
Martin Honnen,


IE5+ provides a
  swapNode
method for nodes in a HTML document.
W3C DOM as implemented by Mozilla doesn't provide such a method but the 
functionality is easy to implement. With Mozilla/NN6 you can prototype 
such a method for Node objects:
<script type="text/javascript; version=1.5">
Node.prototype.swapNode = function (node) {
  var nextSibling = this.nextSibling;
  var parentNode = this.parentNode;
  node.parentNode.replaceChild(this, node);
  parentNode.insertBefore(node, nextSibling);  
}
</script>
As for table rows, swapping them is not different to swapping any other 
nodes. The following example that works with IE5+ and NN6/Mozilla 
contains two paragraphs to swap and a table in which rows can be 
swapped:
<html>
<head>
<script type="text/javascript; version=1.5">
Node.prototype.swapNode = function (node) {
  var nextSibling = this.nextSibling;
  var parentNode = this.parentNode;
  node.parentNode.replaceChild(this, node);
  parentNode.insertBefore(node, nextSibling);  
}
</script>
<script type="text/javascript">
function getSelectedRows (select) {
  var rows = [];
  for (var i = 0; i < select.options.length; i++)
    if (select.options[i].selected)
      rows[rows.length] = i;
  return rows;
}
</script>
</head>
<body>
<p id="p0" style="background-color: red;">
All for Kibology.
</p>
<button onclick="document.getElementById('p0').swapNode
(document.getElementById('p1'))">swap</button>
<p id="p1" style="background-color: green;">
Kibology for all.
</p>
<script type="text/javascript">
var r = Math.floor(Math.random() * 10) + 2;
var html = '';
html += '<table id="aTable" border="1">';
html += '<tbody>';
for (var i = 0; i < r; i++)
  html += '<tr><td>' + i + ' Kibology<\/td><\/tr>';
html += '<\/tbody>';
html += '<\/table>';
document.write(html);
</script>
<form name="gui">
Select two rows to swap:
<script type="text/javascript">
html = '';
html += '<select name="rows" size="' + r + '" multiple="multiple">';
for (var i = 0; i < r; i++)
  html += '<option>row ' + i + '<\/option>';
html += '<\/select>';
document.write(html);
</script>
<input type="button" value="swap rows"
       onclick="var rows = getSelectedRows(this.form.rows);
                var row1 = 
document.getElementById('aTable').rows[rows[0]];
                var row2 = 
document.getElementById('aTable').rows[rows[1]];
                row1.swapNode(row2);"
/>
</form>
</script>
</body>
</html>