I recently wrote a script in which I needed an element to move to the top when it was clicked on. I used, and have been using for years, the following code in the onclick function:
this.parentNode.appendChild(this.parentNode.removeChild(this));
The script wasn’t working, and so I messed around with the code, trying things I’d never done before in an effort to fix it. I thought the problem might lie in this line of code. Actually, it turned out to have nothing to do with it, but while I was tinkering around, I noticed that the following code seems to perform the same function.
this.parentNode.appendChild(this);
As far as I can tell, there is no difference. The former feels “better” to me, but I can’t really say why. Is there an actual difference? If not, I’ll start using the latter and save eighteen characters 🙂
thisis not a child ofthis.You need to remove the child from the parent node.
However,
appendChildwill implicitly remove the node from any existing parent (elements cannot have multiple parents):