简体   繁体   中英

How can I sort divs with javascript

I would like to sort a few divs in ascending order based on their data-id. How can I do that?

<div class="container" data-id="1000">
  <div id="H1"></div>
  <div id="sub">sub 1</div>
  <div id="sub">sub 2</div>
</div>

<div class="container" data-id="3000">
  <div id="H1"></div>
  <div id="sub"></div>
  <div id="sub"></div>
</div>

<div class="container" data-id="2000">
  <div id="H1"></div>
  <div id="sub"></div>
  <div id="sub"></div>
</div>

I've found the solution to my problem a while ago:

function sortOut() {

    // get the classname chapcontainer
    var classname = document.getElementsByClassName('container');

    // create a variable and put the classes it into an array. 
    var divs = [];

    for (var i = 0; i < classname.length; ++i) {
        divs.push(classname[i]);
    }

    // Sort the divs based on data-id. 
    divs.sort(function(a, b) {
        return +a.getAttribute("data-id") - +b.getAttribute("data-id");
    });
};

divs.sort does the trick. More info about this function can be found here:

https://www.w3schools.com/jsref/jsref_sort.asp

Chapname is a variable I get out of a database. Like this:

db.each("SELECT DISTINCT chapname FROM Chapters ORDER BY chaporder", function(err,chapters) 
        { 

          if (err) 
          {console.log('ERROR!', err);}   

          else {
          // create variable
          let chapname = [];
          // push callback 'chapters' into variable 'chapname'
          chapname.push(chapters.chapname);
          // console.log(row);


> This should read like a book: Chapter 1
> - subchapter 1
> - subchapter 2
> 
> Chapter 2
> - subchapter 1
> - subchapter 2
> 
> The problem with above code is that it messes up the sort order of
> chapters. For example when there is a chapter without subchapters. It
> gets queried from the database faster than the previous chapter with
> subchapters.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM