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 interesting problem.
When user uses a smaller resolution than is an optimum the page gets a lot more height. This means it might be useful to change order of some elements (for example some image, search box or navigation) to make the page more readable without much need of scrooling.
So I need to be able to access DOM and change order of some page elements (swap them).
Lets say I have an list and need to swap item 1 and 2.
<ul>
<li>1</li>
<li>2</li>
</ul>
I found a solution based on appending already items elements to <ul>
by using function appendChild
. However there is a problem with text nodes and it gets really complicated to do it for more difficult element structure, since the need of recreating it whole again.
Do you have any suggestion to improve it?
We can reorder HTML elements by using many methods in CSS. We use flexbox's order property. Order property is used to change the visual order and not their logical order. Items in a container are sorted in ascending order value and then by their source code order.
If position: absolute; or position: fixed; - the right property sets the right edge of an element to a unit to the right of the right edge of its nearest positioned ancestor. If position: relative; - the right property sets the right edge of an element to a unit to the left/right of its normal position.
The order property specifies the order of a flexible item relative to the rest of the flexible items inside the same container. Note: If the element is not a flexible item, the order property has no effect.
The order CSS property sets the order to lay out an item in a flex or grid container. Items in a container are sorted by ascending order value and then by their source code order.
For this simple case (swapping the only two elements), you can just use appendChild()
:
(() => {
const list = document.querySelector("ul");
list.appendChild(list.firstElementChild);
})();
<ul>
<li>List-item #1</li>
<li>List-item #2</li>
</ul>
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);
})();
<ul>
<li>Dogs</li>
<li>Snakes</li>
<li>Cats</li>
<li>Bugs</li>
</ul>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With