View the Code & CodePen:
https://dcode.domenade.com/tutorials/how-to-easily-sort-html-tables-with-css-and-javascript

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:
https://www.patreon.com/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

source

29 Comments

  1. 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.

  2. 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);

    });

  3. 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.

  4. 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!

Leave A Reply

Please enter your comment!
Please enter your name here