Search code examples
javascriptsortinggridalphabetical-sort

Alphabetize Grid with... JS? CSS?


I have a grid I'd like to keep in alphabetical order without manually intervening. I.e. that I can continue adding to without re-alphabetizing every time. The grid itself is very simple, just 3 columns with hyperlinks in each 'gridObject'. I'd like the grid to simply be sorted by the link text (or id?) when the page loads, without clicking anything (a document.ready function?).

<style>
    #gridContainer{
        display:grid;
        grid-template-columns: auto auto auto;
        background-color:#420666;
        padding:20px;
    }
    .gridObject{
        min-width: 200px;
        background-color:#666420;
        margin:15px;
        padding:10px;
        color:#fff;
    }
</style>

<div id="gridContainer">
    <div class="gridObject" id="qLink"><a href="">qLink</a></div>
    <div class="gridObject" id="wLink"><a href="">wLink</a></div>
    <div class="gridObject" id="eLink"><a href="">eLink</a></div>
    <div class="gridObject" id="rLink"><a href="">rLink</a></div>
    <div class="gridObject" id="tLink"><a href="">tLink</a></div>
    <div class="gridObject" id="yLink"><a href="">yLink</a></div>
    <div class="gridObject" id="uLink"><a href="">uLink</a></div>
    <div class="gridObject" id="uLink"><a href="">iLink</a></div>
    <div class="gridObject" id="oLink"><a href="">oLink</a></div>
    <div class="gridObject" id="pLink"><a href="">pLink</a></div>
</div>

I was searching for various JS methods to sort arrays, etc, but haven't found anything yet for html tables/grids except making sortable columns. I'm very new to all this so this is very much a learning exercise. Thanks in advance!


Solution

  • Created a sortGrid() function to sort all the element inside the gridObject class to get sorted alphabetically using id's

    // Function based on id of element
    function sortGrid(){
        const gridObject = document.querySelectorAll('.gridObject')
        let array = [];
        gridObject.forEach(grid =>  array.push(grid.getAttribute("id")))
        array.sort()
        array.forEach((item, index) => array[index] = document.querySelector("#"+item))
        const gridContainer = document.querySelector('#gridContainer');
        gridContainer.innerHTML = ""
        array.forEach(grid => gridContainer.innerHTML += grid.outerHTML)
    }
    
     sortGrid()