jQuery Web Development

jQuery DataTable: Sorting dynamic data

Try this code sample online!

Code samples for the this post is available in GitHub and can be previewed live using the link below.


jQuery DataTable is a powerful library to super charge your HTML tables. By default DataTable can sort your data based on the content of the cells. But if you are loading your table data dynamically and want to apply a custom sorting based on the DOM data, you can use DataTable’s custom sorting code:

function applyDomBasedSorting() {
    $.fn.dataTable.ext.order['data-sort'] = function(settings, col) {
        return this.api().column(col, {
            order: 'index'
        }).nodes().map(function(td, i) {
            return $(td).attr('data-sort');

data-sort could be anything. You can define your own sorting logic here. In this example, I would like to sort name by their second names. I’m setting this value into the data-sort attribute of the td cells.

Once you have defined your custom sorting logic like above, then you can use that when initializing your data table.

        "columnDefs": [
          { "orderDataType": "data-sort", "targets": [1]}

GitHub Source code link:

Leave a Reply

Your email address will not be published. Required fields are marked *