'Keep the order in which elements were added
Can anyone advise if there is a way to keep the same order in which elements were added to the #destination after the page refresh? Because once I refresh the page, the order is reset and they are sorted by their index number.
function appendIt(index) {
const element = document.querySelectorAll("div > li")[index];
return function () {
localStorage.setItem("append" + index, "true");
document.getElementById("destination").appendChild(element);
};
}
window.onload = () => {
document
.querySelectorAll("div > li")
.forEach(function (element, index) {
if (localStorage.getItem("append" + index) === "true") {
appendIt(index)();
}
});
};
document.querySelectorAll("div > li")
.forEach(function (element, index) {
element.addEventListener("click", appendIt(index));
});
function clearstorage () {
localStorage.clear();
location.reload();
}
#destination {
display: flex;
flex-direction: column;
background-color: red;
}
#source {
display: flex;
flex-direction: column;
background-color: beige;
}
<div id="app">
<button onclick="clearstorage()">
Reset order
</button>
<div id="destination"></div>
<div id="destination"></div>
<div id="source">
<li id="element0">Zero</li>
<li id="element1">One</li>
<li id="element2">Two</li>
<li id="element3">Three</li>
</div>
</div>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
