Is it possible to swap two HTML DOM nodes?
Let's consider the HTML list below along with a "swap" button:
<ul class="center-text">
<li>0</li>
<li>1</li>
<li>2</li>
</ul>
<form class="center-text">
<button id="swapButton">Swap</button>
</form>
Below is the corresponding JS code:
// using the "ready" method as the only jQuery method in this code
$(document).ready(function(){
document.getElementById("swapButton").onclick = function() {
var ul = document.getElementsByTagName("ul")[0];
// pseudo-swap: inserting "child2" before "child0"
// (indexes are 1 and 5 due to TextNodes between list nodes)
ul.insertBefore(ul.childNodes.item(5), ul.childNodes.item(1));
}
});
Upon clicking the swap button, the items appear to be swapped initially. However, after a short delay (approximately 1/4 of a second), they revert back to their original positions automatically. The question remains: Why does this happen?
Note: The objective here is purely educational, seeking an understanding of the underlying processes without suggesting alternative jQuery methods.