If you're looking to rearrange elements on a webpage, the Node
"API" is your friend. HTML elements are essentially Node
s, and by utilizing methods like firstChild
and insertBefore()
, you can achieve the desired restructuring. One interesting thing I discovered is that inserting a node before itself doesn't seem to cause any issues (at least in Chrome). The added bonus is that when you insert a node elsewhere, it automatically gets unlinked from its previous position. And if you need to move something to the end, there's always appendChild()
for that purpose, which also handles removing it from its original location.
function totop(id){
let first=container.firstChild;
let what=document.getElementById(id);
container.insertBefore(what,first);
}
<div id="container">
<div id="1">one</div>
<div id="2">two</div>
<div id="3">three</div>
</div>
<button onclick="totop(1)">One</button>
<button onclick="totop(2)">Two</button>
<button onclick="totop(3)">Three</button>
(Previous method)
To show/hide elements dynamically, you can simply adjust their styles as follows:
document.getElementById("1").style.display="none";
To hide an element, set the display property to "none"
, and to make it visible again, revert back to the original display value (e.g., "block"
). This technique works seamlessly for toggling visibility on specific elements.