Here is an example script that Recognizes Container Elements (Such As <Div> With A Specific Class Or ID) On Your Website And Sorts Them In Alphabetical Order Based On Their Text Content
<!DOCTYPE html>
<html lang="de">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Container sortieren</title>
<style>
.container {
padding: 10px;
margin: 5px;
border: 1px solid #ccc;
}
</style>
</head>
<body>
<h1>Unsortierte Container</h1>
<div id="container-wrapper">
<div class="container">Banane</div>
<div class="container">Apfel</div>
<div class="container">Orange</div>
<div class="container">Kiwi</div>
<div class="container">Ananas</div>
</div>
<button id="sort-button">Container sortieren</button>
<script>
// Funktion zum Sortieren der Container
function sortContainers() {
const wrapper = document.getElementById('container-wrapper');
const containers = Array.from(wrapper.querySelectorAll('.container'));
// Sortiere die Container alphabetisch nach ihrem Textinhalt
containers.sort((a, b) => a.textContent.localeCompare(b.textContent));
// Entferne die alten Container aus dem Wrapper
wrapper.innerHTML = '';
// Füge die sortierten Container wieder hinzu
containers.forEach(container => wrapper.appendChild(container));
}
// Event Listener für den Button
document.getElementById('sort-button').addEventListener('click', sortContainers);
</script>
</body>
</html>
Explanation:
1. HTML structure:
• There is a wrapper (<div id="container-wrapper">) that contains the containers to be sorted.
• Each container has the container class and contains text that is sorted by.
2. JavaScript function sortContainers:
• All containers within the wrapper are found with querySelectorAll('.container') and converted into an array (Array.from).
• Sorting is done with localeCompare to handle special characters correctly.
• The wrapper is emptied with innerHTML = '' to remove the old elements.
• The sorted containers are added again with appendChild in the correct order.
3. Interactivity:
• A button (id="sort-button") triggers the sorting function.
Result:
• When you click on the button, the containers are sorted alphabetically based on their text content.
Adjustments:
• Do you want other attributes (e.g. Data attributes or id) as a sort criterion, you can customize the sort function, e.g. B.:
containers.sort((a, b) => a.getAttribute('data-name').localeCompare(b.getAttribute('data-name')));
This script works flexibly for any type of container in your code.