とにかく書く

日々の雑感や知り得たことを、とにかく書いています

TABLE の行(tr)の入れ替え

JavaScript で table の行(tr)を入れ替えようと次のように書いたら Node not found っていうエラーが出た。

function swap(a, b) {
	var table = document.getElementById('table_name');
	var clone = table.rows[a].cloneNode(true);
	table.replaceChild(table.rows[b], table.rows[a]);
	table.replaceChild(clone, table.rows[b]);
}

これは rows が table のプロパティに過ぎず、Node ではないから(だと思ってる。)replaceChild は、子ノードを要求する。次のようにしたら問題なくなった。

function swap(a, b) {
	var table = document.getElementById('table_name');
	var cloneA = table.rows[a].cloneNode(true);
	var cloneB = table.rows[b].cloneNode(true);
	table.rows[a].parentNode.replaceChild(cloneB, table.rows[a]);
	table.rows[b].parentNode.replaceChild(cloneA, table.rows[b]);
}

でも、別で指定していた onClick 属性はコピーされない。cloneNode のときに削除されたのか?