Andriuxa Andriuxa - 5 months ago 6
HTML Question

JavaScript - Inserting and sorting elements

I will try to be as specific as i can.
There is a div element on the page that should contain user-list.
Users has the following properties: UserID, UserName, lvl, money.
Line that contains mentioned data contains randomly more HTML formatting.
Each user is added to the

using JavaScript using
operator on
The list is being refreshed once in awhile and new users is added to the bottom.
Every user has its own additional div with
id="uid_" + id
, once user no longer online, he is removed by applying
style.display = "none"
on specific div.
What i'm trying (willing) to do is somehow sort users so the most rich user be on top of the list. This means that users should be inserted to more upper position, or moved to top as list refreshes.

The list HTML may look like that:

<div id='list'>
<div id='uid_1524><font...>UserName</font><...>[15]<...>6587$<...></div>

JavaScript that adds users roughly looks like this:

d.getElementById('list').innerHTML += "<div id='uid.....</div>";

Update function looks for div as element existence and if needed, adds div to list's
, updates
of specific div, or removes div by setting = 'none';

How can i sort existing entries and resolve where next entry should be inserted (and insert it at specific point)


I've solved this question by setting flexfox order property to number of money user has, and set flex-direction: column-reverse;, this way elements with higher order goes on top of the list.

Example of code:

<div id='UserList' style='display:-webkit-flex; display:flex; -webkit-flex-direction:column-reverse; flex-direction:column-reverse;'>


Creating user:

if (!d.getElementById("uid_" + id) {
    // Create a new element, UserNameText should contain entire line with Name, lvl, money, etc.
    d.getElementById("UserList").innerHTML += "<div id='uid_" + id + "' style='-webkit-order:" + UserMoney + "; order: " + UserMoney + ";'>" + UserNameText + "</div>";

Removing user:

if (d.getElementById("uid_" + id) {
    d.getElementById("uid_" + id).style.display = "none"; // Simply hide element

Updating user:

if (d.getElementById("uid_" + id) {
    d.getElementById("uid_" + id).innerHTML = UserNameText; // In case data needs to be updated
    d.getElementById("uid_" + id).style.display = "block"; // In case it was hidden
    d.getElementById("uid_" + id).style.order = UserMoney; // In case position needs to be updated