I am creating a website of floating width. The users use screens from full HD resolution to some 600px on smart phones it seems a pretty good idea. This brings up a very int
For this simple case (swapping the only two elements), you can just use appendChild():
(() => {
const list = document.querySelector("ul");
list.appendChild(list.firstElementChild);
})();
- List-item #1
- List-item #2
The same node cannot exist in multiple positions; so, it's removed from its current position and placed at the end of the collection.
If you want to do more complicated sorting, you probably ought to create an array from the childNodes and get all crazy:
(() => {
const frag = document.createDocumentFragment();
const list = document.querySelector("ul");
const items = list.querySelectorAll("li");
const sortedList = Array.from(items).sort(function(a, b) {
const c = a.textContent,
d = b.textContent;
return c < d ? -1 : c > d ? 1 : 0;
});
for (let item of sortedList) {
frag.appendChild(item);
}
list.appendChild(frag);
})();
- Dogs
- Snakes
- Cats
- Bugs