How to EASILY Sort HTML Tables with CSS & JavaScript - Web Development Tutorial

แชร์
ฝัง
  • เผยแพร่เมื่อ 15 ต.ค. 2024
  • View the Code & CodePen:
    dcode.domenade...
    In this video tutorial I'll be demonstrating how you can use a simple bit of JavaScript to sort your HTML tables - this is super easy to do and is extendable if you'd like to add your own logic to the sorting!
    Support me on Patreon:
    / dcode - with enough funding I plan to develop a website of some sort with a new developer experience!
    Follow me on Twitter @dcodeyt!
    If this video helped you out and you'd like to see more, make sure to leave a like and subscribe to dcode!
    #dcode #webdev #html

ความคิดเห็น • 124

  • @dcode-software
    @dcode-software  4 ปีที่แล้ว +25

    IMPORTANT:
    If working with numerics, I recommend you parse your values to the correct type before comparisons for the most accurate results. For example, using "parseInt" or "parseFloat".
    This is especially important for floats, as you'll get bad results when sorting if they're represented as strings.

    • @krichter9245
      @krichter9245 4 ปีที่แล้ว

      could you change it up in the Source Code that you linked? would really apreciate it because i can't make it work how it should.

    • @krichter9245
      @krichter9245 4 ปีที่แล้ว

      Ok i made it work but now the name won't be sorted correctly..

    • @samuelhowell5962
      @samuelhowell5962 4 ปีที่แล้ว +9

      @@krichter9245 you probably need to sort it differently based on the type of column, here's what I did:
      if (column !== 1) {
      sortedRows = rows.sort((a, b) => {
      const aColText = a.querySelector(`td:nth-child(${ column + 1 })`).textContent.trim();
      const bColText = b.querySelector(`td:nth-child(${ column + 1 })`).textContent.trim();

      return aColText > bColText ? (1 * dirModifier) : (-1 * dirModifier);
      })
      }
      else {
      sortedRows = rows.sort((a, b) => {
      const aColPrice = parseFloat(a.querySelector(`td:nth-child(${ column + 1 })`).textContent.trim().replace('$', ''));
      const bColPrice = parseFloat(b.querySelector(`td:nth-child(${ column + 1 })`).textContent.trim().replace('$', ''));

      return aColPrice > bColPrice ? (1 * dirModifier) : (-1 * dirModifier);
      })
      }if (column !== 1) {
      sortedRows = rows.sort((a, b) => {
      const aColText = a.querySelector(`td:nth-child(${ column + 1 })`).textContent.trim();
      const bColText = b.querySelector(`td:nth-child(${ column + 1 })`).textContent.trim();

      return aColText > bColText ? (1 * dirModifier) : (-1 * dirModifier);
      })
      }
      else {
      sortedRows = rows.sort((a, b) => {
      const aColPrice = parseFloat(a.querySelector(`td:nth-child(${ column + 1 })`).textContent.trim().replace('$', ''));
      const bColPrice = parseFloat(b.querySelector(`td:nth-child(${ column + 1 })`).textContent.trim().replace('$', ''));

      return aColPrice > bColPrice ? (1 * dirModifier) : (-1 * dirModifier);
      })
      }
      so basically I chekced to see if it was the column with numbers in it and sort differently based on that.
      one month late reply idk how useful this will be to you but good luck!

    • @meusingit2137
      @meusingit2137 4 ปีที่แล้ว

      @@samuelhowell5962 Thanks Dude, Take care

    • @jaderzin
      @jaderzin 4 ปีที่แล้ว

      @@samuelhowell5962 It was really useful to me. Thank you!!

  • @partygrouppl
    @partygrouppl 3 ปีที่แล้ว +2

    its easy when you do it, applied and it works, but wouldnt figure out myself. Thanks a lot. Will make use of it for my ajax loaded tables.

  • @vitorpinto8110
    @vitorpinto8110 3 ปีที่แล้ว +1

    Thanks bro. A big hug from Porto (Portugal).

  • @jtkw
    @jtkw 6 หลายเดือนก่อน

    Thanks so much for this.! Is there a way to turn off the sorting capacity for a specific column (e.g.: the last column)?

  • @leonelcenteno3816
    @leonelcenteno3816 2 ปีที่แล้ว

    So good, thank you. In my implentation, table are dynamically produced using AJAX calls. I linked the js at the top as if it were a CDN or something like that and it did not work. I solved it by adding the link to the js right after the script with the AJAX call, just in case someone else encounters a similar problem. Thanks again for this awesome tutorial.

  • @afonsopinto3418
    @afonsopinto3418 4 ปีที่แล้ว +1

    Amazing!!! It helped a lot, It would be much cooler if the table heads add already the sorting icons and each time we clicked on the head cell the corresponding icon would turn to a different color, so people would know that the table is sortable. anyways 5 starts keep it up!!

  • @christianguerrero1110
    @christianguerrero1110 3 ปีที่แล้ว

    Thank you for making a complex issue to me look easy!

  • @lecriptovalute
    @lecriptovalute 2 ปีที่แล้ว +1

    Thank you so very much. For this beautiful tutorial :)

  • @omar2013578
    @omar2013578 2 ปีที่แล้ว +1

    thank >>>you can add toturial for multi filter table depend on html or javascript

  • @minnuss
    @minnuss 2 ปีที่แล้ว

    Great code !!
    I managed to solve the problem with better sorting of numbers, and add some code that can detect if the table is with numbers or letters.

    • @d0gg087
      @d0gg087 ปีที่แล้ว

      please share

  • @mandeep_mehra
    @mandeep_mehra 3 ปีที่แล้ว +2

    how can i use this without click mean , when load the page it automatically sort for first column ???

  • @ankitdedhia8460
    @ankitdedhia8460 3 ปีที่แล้ว

    It works so beautifully! Thanks Man!

  • @daedalusrasmus3278
    @daedalusrasmus3278 4 ปีที่แล้ว +3

    I think there's a problem with case-sensitive entries, they seem to prioritize capitalized/upper-cased letters than lower-cased ones

  • @kevinmorte3959
    @kevinmorte3959 3 ปีที่แล้ว +2

    Very eloquent video, as usual. Just a quick question: instead of concatate .parentElement, would'nt be more effiicient to use .closes()? In that way, you don't have to previously be aware hay many levels there are from th to table. (and less code redundancy, maybe);
    Thanks for this videos, btw!

  • @freizeitreiten
    @freizeitreiten 2 ปีที่แล้ว +1

    great job, thx for showing!

  • @TownleyVM
    @TownleyVM ปีที่แล้ว

    So cool. Thank you. I got it to work with my php table as well and it works almost perfect. Sorting names, no problem, sorting numbers its a little fiddly though.

    • @michaelwang1524
      @michaelwang1524 ปีที่แล้ว +3

      hey idk if this helps you sort the numbers
      const sortedRows = rows.sort((a, b) => {
      const aColText = a.querySelector(`td:nth-child(${ column + 1})`).textContent.trim();
      const bColText = b.querySelector(`td:nth-child(${ column + 1})`).textContent.trim();
      const aNum = parseInt(aColText);
      const bNum = parseInt(bColText);
      return (aNum - bNum) > 0 ? (1 * dirModifier) : (-1 * dirModifier);
      });

    • @TownleyVM
      @TownleyVM ปีที่แล้ว

      @@michaelwang1524 Thank you so much. That totally worked. Greatly appreciated.

    • @michaelwang1524
      @michaelwang1524 ปีที่แล้ว

      @@TownleyVM You know what we should totally work together if ur also building a website so we can bounce ideas off of each other.

    • @lachlanpirie899
      @lachlanpirie899 ปีที่แล้ว

      @@michaelwang1524 I had this problem too and this sorted it, thank you! My first column is made up of strings and the rest numbers so I added an if statement to differentiate between your return code and the one used in the video.

  • @jeslyndanielleella408
    @jeslyndanielleella408 7 หลายเดือนก่อน

    Hello, I'm using this code and it works very well. However, when I use it on paginated tables, it will only sort the rows found on the current page. I want it to sort all the rows. Please help.

  • @VIDEORealism
    @VIDEORealism 8 หลายเดือนก่อน

    great video for a complete .js noob like me even though it didn't work for me and I don't not finde the mistake I made, so I had to copy your script from code pen... at least I tried XD Im wondering how to put the table back in the original sequence as it was before sorting without reloading the site? the tables at wikipedia for example do have this 3 states for each column - asc, desc and back to original...

  • @miltont5173
    @miltont5173 3 ปีที่แล้ว +1

    Awesome work, is it possible to filter on the name column?
    Would you consider doing a follow-up video on how to do this if possible please?

  • @michealkinney6205
    @michealkinney6205 ปีที่แล้ว

    Very helpful reference. Thank you!

  • @CaitlinFlynn-b3y
    @CaitlinFlynn-b3y ปีที่แล้ว

    Hello! I was wondering if you could tell me, how would you edit your table to only sort one column? I imagine it would be in headerCell function. Would you edit the tableElement variable? Or would it be in the document.querySelectorAll(".table-sortable th") part? Thank you so much if you could help me with this!

  • @Pedro-gu7jj
    @Pedro-gu7jj 3 ปีที่แล้ว

    Bro, you resolve my problem , thanks for that! new sub

  • @AlvaroErnestoSanchezVega
    @AlvaroErnestoSanchezVega 10 หลายเดือนก่อน

    thank you very much, the code is super functional.

  • @ponedtonever
    @ponedtonever ปีที่แล้ว

    Thank you! This video helped me sort my table lol

  • @nihilanz4097
    @nihilanz4097 ปีที่แล้ว

    Thank you for this video. Very well done!

  • @hafizjavaid
    @hafizjavaid 4 ปีที่แล้ว +2

    Thanks man for this information. Keep it up

  • @Makc199710
    @Makc199710 3 ปีที่แล้ว +1

    Thank you it's the best lesson that I ever seen)))))

  • @brianbrowni
    @brianbrowni ปีที่แล้ว

    do I have a possibility not to sort the Rank? let the rank fix?

  • @rafaelefstathiou7516
    @rafaelefstathiou7516 4 ปีที่แล้ว +1

    Great help and amazing explanation! The question is how can i do this beautiful sorting you did using DropDown menus and Select Tags?

  • @aurasolis9928
    @aurasolis9928 3 ปีที่แล้ว

    Awesome video! I’m making a project and I want to do this but whit an input, so the client select the csv file and displays in the srcren

  • @zycro8084
    @zycro8084 3 ปีที่แล้ว

    Thanks for the amazing tutorial, helped a lot!

  • @tradewinds9832
    @tradewinds9832 4 ปีที่แล้ว

    Excellent mate. Thanks for sharing.

  • @geethac2707
    @geethac2707 3 ปีที่แล้ว

    Awesome video! How do you make it sort selected values from a dropdown column? Thanks!!

  • @jaderzin
    @jaderzin 4 ปีที่แล้ว

    Do I have to change anything to make this work with flask? Mine isn't working. Nothing happens =(

  • @ourfamilygarden
    @ourfamilygarden 5 หลายเดือนก่อน

    Amazing tutorial!

  • @abanwaraphael1526
    @abanwaraphael1526 2 ปีที่แล้ว

    Great video but Does this work on pagination?

  • @Pyraptor
    @Pyraptor 4 ปีที่แล้ว +2

    Thanks! I'm tired of using CSS libraries

  • @henrychoy7342
    @henrychoy7342 3 ปีที่แล้ว

    Thanks fort this! But the code doesn't seem to work if the table is populated with AJAX?

  • @maksimbronsky7117
    @maksimbronsky7117 3 ปีที่แล้ว

    @dcode Why is that video part of the JavaScript Classes playlist?

  • @sandarateng785
    @sandarateng785 4 ปีที่แล้ว +2

    Thanks mate! Keep it up!

  • @TriinTamburiin
    @TriinTamburiin 3 ปีที่แล้ว +3

    Instead of traversing DOM one by one like:
    const tableElement = headerCell.parentElement.parentElement.parentElement;
    It's easier just to use closest() method.
    const tableElement = headerCell.closest('.table');

    • @dcode-software
      @dcode-software  3 ปีที่แล้ว +1

      That's a much better solution. I've been using it in my recent videos. Thanks 😀

  • @jaafaryusuf1444
    @jaafaryusuf1444 3 ปีที่แล้ว

    Hello, what if I want to work with table that requires calculations?

  • @James-ml5mu
    @James-ml5mu 3 ปีที่แล้ว

    Thank you for this video!

  • @summaalchemica364
    @summaalchemica364 ปีที่แล้ว

    Awesome, thanks

  • @ktr66
    @ktr66 3 ปีที่แล้ว +1

    Thanks for posting this tutorial, it is fantastic! What part o the code would I change to have the first column click present the descending order?

    • @ktr66
      @ktr66 3 ปีที่แล้ว +1

      Thanks again for great video and code. I figured it out. I set the 'asc' parameter to 'false' in the sortTableByColumn function and also named the const dirModifier = asc ? from 1 : -1 to -1 : 1

  • @ANDREANEVE-r3z
    @ANDREANEVE-r3z ปีที่แล้ว

    thanks it works great

  • @slavicakaraterzieva3257
    @slavicakaraterzieva3257 4 ปีที่แล้ว

    I get error in declaring the constants, like: sortedRows is declared but it's value is never read. I'm all day on it trying to solve it. I'm using visual studio 2017. Help please anybody?

  • @investontech3916
    @investontech3916 3 ปีที่แล้ว

    when i try inspect its working but its not sorting. need help please

  • @yorker3148
    @yorker3148 2 ปีที่แล้ว

    thanks ! very helpful

  • @mohammedkalim7642
    @mohammedkalim7642 3 ปีที่แล้ว

    Really amazing and thanks for making this

  • @emmanuellefrappier4651
    @emmanuellefrappier4651 3 ปีที่แล้ว

    if i don't want to sort all the columns, what should i change please?

  • @Mo-po3gh
    @Mo-po3gh 2 ปีที่แล้ว

    you are awesome dude

  • @Usernameiswadum
    @Usernameiswadum 4 ปีที่แล้ว +1

    Thank you so much! :)

    • @dcode-software
      @dcode-software  3 ปีที่แล้ว

      You're welcome, glad it could help

  • @tarunpatel1827
    @tarunpatel1827 3 ปีที่แล้ว

    Great tutorial thanks!!
    Can you also do a tutorial on pagination

  • @nicolebenedictlim9393
    @nicolebenedictlim9393 4 ปีที่แล้ว +1

    Thanks for sharing this will help a lot for my current project , but there's a line of code that I cannot understand please see below:
    return aColText > bColText ? (1 * dirModifier) : (-1 * dirModifier);
    what does this code mean ? thanks !

    • @dcode-software
      @dcode-software  4 ปีที่แล้ว +3

      It's using the ternary operator: developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/Conditional_Operator
      We want either -1 or 1, and the dirModifier flips number (-1 or 1) depending on if we are sorting ascending or descending

    • @nicolebenedictlim9393
      @nicolebenedictlim9393 4 ปีที่แล้ว

      @@dcode-software thank you sir

  • @swathikrishnan3956
    @swathikrishnan3956 2 ปีที่แล้ว

    How to increase size of that sort arrow

  • @swara_dange09
    @swara_dange09 3 ปีที่แล้ว

    how to sort table column based on dropdown option

  • @markreeves5561
    @markreeves5561 4 ปีที่แล้ว +1

    Thanks for the tutorial. It's great. It Just helped me in my project

  • @AndriusAndrulionis
    @AndriusAndrulionis 4 ปีที่แล้ว +1

    If numbers are more than 10 it sorting 1 10 11 2 3 4... or 9...3 2 11 10 1 it's ok if writing 01 02 03... :)

  • @hazara4831
    @hazara4831 2 ปีที่แล้ว

    How can I do pagination?

  • @petco605
    @petco605 ปีที่แล้ว

    I followed the video and my sorting doesnt work :(

  • @MrFyce
    @MrFyce 3 ปีที่แล้ว

    how to integrate this with mysql?

  • @skiiiworld6205
    @skiiiworld6205 ปีที่แล้ว

    everything works for me but not the CSS i dont know why anyone having issue applying css arrows doesnot appear?

  • @kasvith
    @kasvith 4 ปีที่แล้ว

    Can you do this with Vue? would be awesome

  • @sirmonke
    @sirmonke 4 ปีที่แล้ว

    can i also sort certain categories(dates dont function)

    • @vidhyas806
      @vidhyas806 3 ปีที่แล้ว

      did u get the solution?

  • @jdubhman
    @jdubhman 3 ปีที่แล้ว

    Cheers mate 🍻

  • @michaelwang1524
    @michaelwang1524 ปีที่แล้ว +1

    Sort by numbers only
    const sortedRows = rows.sort((a, b) => {
    const aColText = a.querySelector(`td:nth-child(${ column + 1})`).textContent.trim();
    const bColText = b.querySelector(`td:nth-child(${ column + 1})`).textContent.trim();
    const aNum = parseInt(aColText);
    const bNum = parseInt(bColText);
    return (aNum - bNum) > 0 ? (1 * dirModifier) : (-1 * dirModifier);
    });

  • @KilconL
    @KilconL 3 ปีที่แล้ว

    Clicked subs and love you

  • @yumincao9209
    @yumincao9209 3 ปีที่แล้ว

    Thank you!!! :-D

  • @Rrs774
    @Rrs774 4 ปีที่แล้ว

    How can you keep the ranking order unchanged ?

    • @dcode-software
      @dcode-software  4 ปีที่แล้ว

      You could make use of something like Local Storage or Session Storage

    • @Rrs774
      @Rrs774 4 ปีที่แล้ว

      I made it work with a forEach on every row to keep the index before adding to the empty table...thank you for the quick reply:D

  • @demodemo-q8l
    @demodemo-q8l ปีที่แล้ว

    not working in paginations

  • @רותיכהן-מ7ר
    @רותיכהן-מ7ר 3 ปีที่แล้ว

    You are awesomeeeeeeeeeeeeeee!!!! thx

  • @Nice4Nice
    @Nice4Nice 3 ปีที่แล้ว

    Great

  • @powerstar61
    @powerstar61 2 ปีที่แล้ว

    Bro, please share code

  • @GrumpyOldMan9
    @GrumpyOldMan9 3 ปีที่แล้ว

    Easy. Yeah, right.

  • @ninam7749
    @ninam7749 2 ปีที่แล้ว

    🙏🏽🙏🏽🙏🏽

  • @ilovecoffee7623
    @ilovecoffee7623 3 ปีที่แล้ว +5

    Why are you using such a convoluted and complex way of getting the index of each clicked 'TH', when you can just use the 'index' argument of forEach() instead? Instead of this: const headerIndex = Array.prototype.indexOf.call(headerCell.parentElement.children, headerCell), you can just pass 'index' argument, and then assign it to headerIndex.

    • @powerstar61
      @powerstar61 2 ปีที่แล้ว

      Hi,
      Can you share full code please

  • @ryrilya2289
    @ryrilya2289 3 ปีที่แล้ว

    This was very useful, thanks a lot!

  • @designwithdiv
    @designwithdiv 3 ปีที่แล้ว

    How to pagination with it?