Home > other >  Sort div element using jQuery?
Sort div element using jQuery?

Time:09-25

i have the following html structure:

<div id='main'>
    <div id='612'>
    </div>
    ...
    <div id='1'>
    </div>
</div>

As you can see i have several div going in a decreasing order and i wuold like to make a button that activate a jQuery script that can sort those div in both ways (decreasing and increasing). I already created the button and linked it to the script but i can't find a way to sort the divs. Is possible?

Edit: Posted the entire code on pastebin: https://pastebin.com/DZWdNMZk

CodePudding user response:

This is one option. Setting the display of the parent to flex, then using js to set the order property of the children. Hopefully the demonstration helps!

document.querySelector("#orderEm")
  .addEventListener("click", () => {
    document.querySelectorAll("div > div")
      .forEach(div => {
        div.style.order = div.id;
      });
  });
document.querySelector("#reverse")
  .addEventListener("click", () => {
    document.querySelector("#container")
      .classList.toggle("reverse");
  });
#container {
  display: flex;
  justify-content: space-around;
}

#container.reverse {
  flex-direction: row-reverse;
}

div > div {
  height: 50px;
  width: 50px;
  font-size: 15pt;
  border: 1px solid black;
  margin: 1em;
  
  display: flex;
  justify-content: center;
  align-items: center;
}
<div id="container" data-sorted="unsorted">
  <div id="2">2</div>
  <div id="3">3</div>
  <div id="1">1</div>
</div>
<button id="orderEm">Order 'Em!</button>
<button id="reverse">Reverse 'Em!</button>

CodePudding user response:

One of of doing this is to get the elements into an array and sort the array and re-append them to the main div:

$('#btnAsc').click(function() {
  //gets all div children of the main div, this returns a jQuery array with the elements
    var divs = $('#main div');
  //sorts the divs based on the id attribute
  var ordered = divs.sort(function(a, b) {
    return $(a).attr('id') - $(b).attr('id');
  });
  //empty the main div and re-append the ordered divs
  $('#main').empty().append(ordered)
});

$('#btnDesc').click(function(){
    var divs = $('#main div');
  var ordered = divs.sort(function(a, b) {
    return $(b).attr('id') - $(a).attr('id');
  });
  $('#main').empty().append(ordered)
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id='main'>
    <div id='612'>
      612
    </div>
    <div id='1'>
    1
    </div>
     <div id='2'>
    2
    </div>
     <div id='3'>
    3
    </div>
     <div id='5'>
    5
    </div>
</div>


<input type="button" id="btnAsc" value="Asc">
<input type="button"  id="btnDesc" value="Desc">

  • Related