Exit
  • Global community
    • Language:
      • Deutsch
      • English
      • Español
      • Français
      • Português
  • 日本語コミュニティ
  • 한국 커뮤니티
0

Can an ordered list be re-ordered without using a database?

Engaged ,
Jan 22, 2025 Jan 22, 2025

More designer than coder here; pretty decent with html/css, with a sprinkle of php (for string/file includes). Zero experience or knowledge of MySQL or databases in general, however.

 

I was wondering, is there a way to re-order an ordered list alphabetically without using databases?


In other words, turn this :

1. Blue Turtle (Josh Adams)
2. Devo (Devin Salam)
3. Champ (Mike Thompson)
etc.


Into this :

1. Blue Turtle (Josh Adams)
2. Champ (Mike Thompson)
3. Devo (Devin Salam)
etc.

...and vice-versa, via [Alphabetical] + [Original Order] buttons at the top.

 

I can imagine this being easy as pie using a database, but is there a way to re-order the list without one?

262
Translate
Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines
Community Expert ,
Jan 22, 2025 Jan 22, 2025

Try

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Reorder List</title>
</head>
<body>
    <button onclick="sortAlphabetically()">Alphabetical</button>
    <button onclick="sortOriginal()">Original Order</button>

    <ol id="myList">
        <li>Blue Turtle (Josh Adams)</li>
        <li>Devo (Devin Salam)</li>
        <li>Champ (Mike Thompson)</li>
    </ol>

    <script>
        // Store the original order
        const originalListItems = Array.from(document.querySelectorAll("#myList li"));
        
        // Function to sort the list alphabetically
        function sortAlphabetically() {
            const list = document.getElementById("myList");
            const items = Array.from(list.querySelectorAll("li"));

            items.sort((a, b) => a.textContent.localeCompare(b.textContent));

            while (list.firstChild) {
                list.removeChild(list.firstChild);
            }

            items.forEach(item => {
                list.appendChild(item);
            });
        }

        // Function to sort the list back to the original order
        function sortOriginal() {
            const list = document.getElementById("myList");

            while (list.firstChild) {
                list.removeChild(list.firstChild);
            }

            originalListItems.forEach(item => {
                list.appendChild(item);
            });
        }
    </script>
</body>
</html>
Wappler is the DMXzone-made Dreamweaver replacement and includes the best of their powerful extensions, as well as much more!
Translate
Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines
Community Expert ,
Jan 22, 2025 Jan 22, 2025

@BenPleysier  code is already well-functioning and very clear, but it's not necessary to remove and append elements in each loop (a while followed by a forEach).

 

 

 

// OL references
const myList = document.getElementById("myList");

// Original & Alphabetical references
const originalList = Array.from(myList.children);
const alphabeticalList = [...originalList].sort((a, b) =>
     a.textContent.localeCompare(b.textContent)
);

// Rendering function
function renderList(items) {
     myList.innerHTML = "";
     items.forEach(item => myList.appendChild(item));
}

// Button events
document.getElementById("btnAlpha").addEventListener("click", () => renderList(alphabeticalList));
document.getElementById("btnOriginal").addEventListener("click", () => renderList(originalList));

 

 

You can access by https://demo.puce-et-media.com/UnderS/tri-0.html

 

Translate
Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines
LEGEND ,
Jan 23, 2025 Jan 23, 2025

I'll throw this solution into the ring (store your list in a javascript array).......

 

 

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Sort List Alphabetically</title>
</head>
<body>

<button class="sort" onclick="sortedList()">Alphabetical</button>
<button class="sort" onclick="defaultList()">Original</button>
<ul class="listItems"></ul>

<script>

const list = [
'Blue Turtle (Josh Adams)',
'Devo (Devin Salam)',
'Champ (Mike Thompson)'
];

const listItems = document.querySelector('.listItems')

// Original unsorted list function
function defaultList() {
listItems.innerHTML = '';
list.forEach((list) => {
listItems.innerHTML += `<li>${list}</li>`;
})
}

// Sorted list function
function sortedList() {
listItems.innerHTML = '';
list.toSorted().forEach((sorted) => {
listItems.innerHTML += `<li>${sorted}</li>`;
})
}

// Run original unsorted list on page load
defaultList();

</script>

</body>
</html>

 

 

Translate
Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines
Community Expert ,
Jan 23, 2025 Jan 23, 2025

Using a JSON dataset, as per @osgood_, you could have something like this, where clicking on the header, sorts the column.

 

<!DOCTYPE html>
<html lang="en">

<head>
    <base href="/">
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Sortable List</title>
    <style>
        table {
            width: 100%;
            border-collapse: collapse;
        }

        th,
        td {
            padding: 10px;
            border: 1px solid #000;
            text-align: left;
        }

        th {
            cursor: pointer;
        }
    </style>
</head>

<body>
    <h1>Sortable List</h1>
    <table id="data-table">
        <thead>
            <tr>
                <th onclick="sortTable(0)">ID</th>
                <th onclick="sortTable(1)">Title</th>
                <th onclick="sortTable(2)">Name</th>
            </tr>
        </thead>
        <tbody>
            <!-- Data will be inserted here -->
        </tbody>
    </table>
    <script>
        const jsonData = {
            "list": [
                { "ID": 1, "Title": "Blue Turtle", "Name": "Josh Adams" },
                { "ID": 2, "Title": "Devo", "Name": "Devin Salam" },
                { "ID": 3, "Title": "Champ", "Name": "Mike Thompson" }
            ]
        };

        function populateTable(data) {
            const tableBody = document.querySelector('#data-table tbody');
            tableBody.innerHTML = '';

            data.forEach(item => {
                const row = document.createElement('tr');
                row.innerHTML = `
                    <td>${item.ID}</td>
                    <td>${item.Title}</td>
                    <td>${item.Name}</td>
                `;
                tableBody.appendChild(row);
            });
        }

        function sortTable(columnIndex) {
            const data = [...jsonData.list];
            data.sort((a, b) => {
                const textA = Object.values(a)[columnIndex].toString().toLowerCase();
                const textB = Object.values(b)[columnIndex].toString().toLowerCase();
                return textA < textB ? -1 : textA > textB ? 1 : 0;
            });
            populateTable(data);
        }

        // Initial population of the table
        populateTable(jsonData.list);
    </script>
</body>

</html>

 

 

 

Wappler is the DMXzone-made Dreamweaver replacement and includes the best of their powerful extensions, as well as much more!
Translate
Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines
New Here ,
Jan 24, 2025 Jan 24, 2025
LATEST

You can reorder an HTML list alphabetically or reset it to the original order using JavaScript. Here's a short example:

HTML & JavaScript

<ol id="myList">
    <li>Blue Turtle (Josh Adams)</li>
    <li>Devo (Devin Salam)</li>
    <li>Champ (Mike Thompson)</li>
</ol>
<button onclick="sortList()">Sort Alphabetically</button>
<button onclick="resetList()">Original Order</button>

<script>
    const originalList = Array.from(document.querySelectorAll("#myList li")).map(li => li.textContent);

    function sortList() {
        const list = document.getElementById("myList");
        const items = Array.from(list.querySelectorAll("li"));
        items.sort((a, b) => a.textContent.localeCompare(b.textContent));
        list.innerHTML = "";
        items.forEach(item => list.appendChild(item));
    }

    function resetList() {
        const list = document.getElementById("myList");
        list.innerHTML = "";
        originalList.forEach(text => {
            const li = document.createElement("li");
            li.textContent = text;
            list.appendChild(li);
        });
    }
</script>

How It Works

  1. Store Original Order: Save the initial list items in an array.
  2. Sort Button: Sort list items alphabetically and re-add them.
  3. Reset Button: Restore the list from the saved original order.

No database needed! Everything happens in the browser.

Onlive Server
Translate
Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines