Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I'm trying to order divs in html based on the id of them

I have a div, with lots of other divs inside, each with a button inside that. I need to order the divs inside the main div, based on their id, but without using jQuery or anything, just clean and simple JavaScript. I can't find any way to do this, so any suggestions would be greatly appreciated.

I have been on lots of websites that show solutions for doing it based on the text within the div but not by the id.

function sortDiv() {
    var mainDiv = document.getElementById("divsGroup");
    var divs = mainDiv.children;
    for (i = 0; i < divs.length(); i++) {
        if //divs[i] is higher in the alphabet than divs[i+1] then  {
            //rearrange the divs 
        };
    };
};

I need the divs to be rearranged so they're displayed based on their id, alphabetically.

like image 958
benbayliss24 Avatar asked Dec 08 '25 09:12

benbayliss24


2 Answers

Here's a solution where the sorting bit is handled in a simple Array of id strings. Then, for each id (already in alphabetical order), we loop through the divs to find the next one to (re-)insert into the DOM.

document.getElementById("sortBtn").addEventListener("click", sortDivs);

function sortDivs(){
  let mainDiv = document.getElementById("divsGroup"),
      divs = mainDiv.children,
  // `[...divs]` converts `divs` to an Array so we can use the `.map` and `.sort` methods
  divsArray = [...divs];
  // `.map(div => div.id )` makes a new Array of all the `id` strings, and
  // `.sort()` sorts the new Array alphabetically
  idList = divsArray.map(div => div.id).sort();

  //console.log(idList); // logs ["a", "b", "c", "d" ]

  // `idList` and `divsArray` are Arrays, so we can also use 
  //    the `.forEach` method to loop through them
  idList.forEach(id => {
    // As we process each `id` alphabetically, we check each `div`'s id for a match 
    divsArray.forEach(div => {
      if(div.id == id){ // Finds div with matching id
        mainDiv.appendChild(div); // Moves the matching div to bottom of `mainDiv`
      }
    });
  });
}
<div id="divsGroup">
  <div id="d">-d-</div>
  <div id="b">-b-</div>
  <div id="c">-c-</div>
  <div id="a">-a-</div>
</div>
<button id="sortBtn">Sort 'em</button>

Note: This code could be shorter, but for anyone unfamiliar with the .map and .forEach methods of Array, or with the spread operator (...), this lengthier version may help make things more clear.

like image 138
Cat Avatar answered Dec 10 '25 21:12

Cat


You can use javascript arrays sort to sort nodes like this:

<div id="main">
  <div id="9"><button>9</button></div>
  <div id="2"><button>2</button></div>
  <div id="3"><button>3</button></div>
  <div id="4"><button>4</button></div>
  <div id="5"><button>5</button></div>
  <div id="1"><button>1</button></div>
  <div id="6"><button>6</button></div>
  <div id="7"><button>7</button></div>
  <div id="8"><button>8</button></div>
</div>
let parentNode = document.getElementById("main");
var e = parentNode.children;
[].slice
  .call(e)
  .sort(function(a, b) {
    return a.id.localeCompare(b.id);
  })
  .forEach(function(val, index) {
    parentNode.appendChild(val);
  });

Like this you can sort by any attribute, for example you can sort by textContent of those elements or any other property. here's a pen: https://codepen.io/wyzix33/pen/XvpWBg Hope it helps

like image 32
Gabriel Avatar answered Dec 10 '25 22:12

Gabriel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!