Search code examples
javascriptdom

Why are changes to the page DOM performed by a form button automatically reverted after a while?


What i want to do is swapping two HTML DOM nodes.

Let's take the following HTML list and the swap button below:

    <ul class="center-text">
        <li>0</li>
        <li>1</li>
        <li>2</li>
    </ul>

    <form class="center-text">
        <button id="swapButton">Swap</button>
    </form>

And here is my JS code:

// the "ready" method is the only jQuery method used in the code
$(document).ready(function(){
    document.getElementById("swapButton").onclick = function() {
        var ul = document.getElementsByTagName("ul")[0];

        // pseudo-swapping: insert "child2" before "child0"
        // (indexes are 1 and 5 because of the TextNodes between list nodes)
        ul.insertBefore(ul.childNodes.item(5), ul.childNodes.item(1));                      
    }
});

So here is what happens when clicking the swap button:
The items are swaped indeed. But Somehow after (let's say 1/4) seconds they are restored to their original position, i.e. swaped back automatically. My question is: WHY?

PS: the code is merely for educational purposes and i only try to understand what's going on behind the doors, so please do NOT post any alternative jQuery method.


Solution

  • $(document).ready(function(){
        document.getElementById("swapButton").onclick = function(e) {
            e.preventDefault();
            var ul = document.getElementsByTagName("ul")[0];
            ul.insertBefore(ul.childNodes.item(5), ul.childNodes.item(1));                      
        }
    });
    

    This is because button redirects the page to same page. And reverts all. You need to prevent the default behaviour of button.