SweetTable.js Documentation

A lightweight, flexible, dependency free JavaScript library that enables sorting functionality for standard HTML tables and custom table-like structures (e.g., div-based, ul/ol-based tables).

Feature Comparison

Feature SourTable.js SweetTable.js
Table Support Standard HTML tables only (<table>) Standard HTML tables AND custom structures (div, ul, ol, etc.)
Initialization Simple initialization for standard tables Requires additional setup for custom table structures
Custom Parsers Supports custom parse functions for columns Supports custom parse functions for columns
Attribute Sorting Supports sorting by data attributes Supports sorting by data attributes
Column Exclusion Supports excluding columns from sorting Supports excluding columns from sorting
Customization Required None for standard tables Must define 4 custom functions for non-table elements:
  • setCustomGetHeadersFunction
  • setCustomGetRowsFunction
  • setCustomGetTbodyFunction
  • setCustomGetCellFromRowFunction
Performance Optimized for standard tables Slightly slower with custom structures due to additional function calls

Recommendations

When to Use SourTable.js

  • When working with standard HTML <table> elements
  • When you need a simple, lightweight solution
  • When you don't need to support custom table structures

When to Use SweetTable.js

  • When you need to sort non-table elements (div, ul, ol, etc.)
  • When you need more flexible table structure handling
  • When you can accept slightly more complex initialization

1. Constructor

new SweetTable(tableElement, excludedColumns = [], keysForAttributes = {})

Initializes a new SweetTable instance.

Parameters

Parameter Type Required? Description
tableElement HTMLElement Yes The table element (or table-like structure) to make sortable.
excludedColumns Array<number> No Array of column indexes (0-based) to exclude from sorting.
keysForAttributes Object No Maps column indexes to data attributes for sorting (e.g., { "col_2": 'data-date' }).

Usage Example

// Basic initialization
        const table = document.getElementById('my-table');
        const sweetTable = new SweetTable(table);
        
        // Exclude columns 1 and 3, sort column 2 by 'data-price' attribute
        const sweetTableAdvanced = new SweetTable(table, [1, 3], {"col_2": 'data-price' });

Throws Errors If:

  • tableElement is not a valid HTMLElement.
  • excludedColumns is not an array of integers.
  • keysForAttributes is not an object.

2. Core Methods

initiate()

sweetTable.initiate()

Mandatory for all use cases. Enables sorting functionality on the table.

Usage Example


const sweetTable = new SweetTable(table);
sweetTable.initiate(); // Now the table is sortable

Throws Errors If:

  • The table is already initialized (sweettable-initiated class exists).
  • Required custom functions are missing (for non-standard tables).

disengage()

sweetTable.disengage()

Optional but recommended for cleanup. Removes sorting functionality and event listeners.

Usage Example


if (sweetTable && sweetTable.isEngaged()) {
    sweetTable.disengage();
    sweetTable = null;
}

When to Use:

  • When dynamically removing/replacing tables.
  • To prevent memory leaks in single-page applications.

isEngaged()

sweetTable.isEngaged()

Optional for checking state. Returns true if a SweetTable instance exists on that variable, false otherwise.

Usage Example


if (sweetTable.isEngaged()) {
    console.log("Table is sortable!");
}

3. Customization Methods

For Standard HTML Tables (<table>)

These methods are optional since SweetTable automatically detects most of standard HTML tables.

setCustomParseFunction(colIndex, parseFunction)

sweetTable.setCustomParseFunction(colIndex, parseFunction)

Applies a custom parser for a specific column.

Parameter Type Required? Description
colIndex number Yes Column index (0-based).
parseFunction (text: string) => any Yes Function that converts text into a sortable value.

Usage Example

// Parse dates in "MM/DD/YYYY" format
        sweetTable.setCustomParseFunction(3, (text) => {
            const parts = text.split('/');
            return new Date(parts[2], parts[0] - 1, parts[1]).getTime();
        });

For Non-Standard Tables (div, ul, ol, etc.)

These methods are mandatory for custom table structures.

setCustomGetHeadersFunction(func)

sweetTable.setCustomGetHeadersFunction(func)

This function defines how to get the header cells from a table.

Just to help it understand, if we were working with a standard HTML <table> element, this function would take the table as argument and return all <th> elements as a NodeList or an array.

Function: (table: HTMLElement) => NodeList/Array

setCustomGetRowsFunction(func)

sweetTable.setCustomGetRowsFunction(func)

Defines how to retrieve table rows.

Just to help it understand, if we were working with a standard HTML <table> element, this function would take the table as argument and return all the rows elements in tbody (eg: document.querySelectorAll("tbody tr")) as a NodeList or an array.

Function: (table: HTMLElement) => NodeList/Array

setCustomGetTbodyFunction(func)

sweetTable.setCustomGetTbodyFunction(func)

Defines the container/parent element for rows (for DOM reordering).

For example: in standard HTML tables, the <tbody> acts as the container/parent of all the rows

Function: (table: HTMLElement) => HTMLElement

setCustomGetCellFromRowFunction(func)

sweetTable.setCustomGetCellFromRowFunction(func)

Defines how to extract cells from a row.

Just to help it understand, if we were working with a standard HTML <table> element, this function would take the tr element as argument and return all <td> elements in that row as a NodeList or an array.

Function: (row: HTMLElement) => NodeList/Array

Full Example for a div-based Table


<div class="div-table" id="div-table">
    <div class="div-header">
        <div class="div-th">Product</div>
        <div class="div-th">Category</div>
        <div class="div-th">Price</div>
        <div class="div-th">Stock</div>
    </div>
    <div class="div-body">
        <div class="div-tr">
            <div class="div-td">Laptop</div>
            <div class="div-td">Electronics</div>
            <div class="div-td">$999.99</div>
            <div class="div-td">15</div>
        </div>
        <div class="div-tr">
            <div class="div-td">Desk Chair</div>
            <div class="div-td">Furniture</div>
            <div class="div-td">$149.99</div>
            <div class="div-td">8</div>
        </div>
        <div class="div-tr">
            <div class="div-td">Monitor</div>
            <div class="div-td">Electronics</div>
            <div class="div-td">$249.99</div>
            <div class="div-td">12</div>
        </div>
    </div>
</div>                        
                        

let divSweetTable;

function initDivTable() {
    const divTable = document.getElementById('div-table');

    divSweetTable = new SweetTable(divTable);

    divSweetTable.setCustomGetHeadersFunction((table) => {
        return table.querySelectorAll('.div-th');
    });

    divSweetTable.setCustomGetRowsFunction((table) => {
       return table.querySelectorAll('.div-tr');
    });

    divSweetTable.setCustomGetTbodyFunction((table) => {
        return table.querySelector('.div-body');
    });

    divSweetTable.setCustomGetCellFromRowFunction((row) => {
        return row.querySelectorAll('.div-td');
    });

    // Custom parsing for price column (index 2)
    divSweetTable.setCustomParseFunction(2, (text) => {
        return parseFloat(text.replace(/[$,]/g, ''));
    });

    divSweetTable.initiate();
}

function disengageDivTable() {
    if (divSweetTable && divSweetTable.isEngaged()) {
        divSweetTable.disengage();
        divSweetTable = null;
    }
}
                    

4. Programmatic Sorting

sort(colIndex, order, key = "")

sweetTable.sort(colIndex, order, key = "")

Optional for manual sorting control.

Parameter Type Required? Description
colIndex number Yes Column index (0-based).
order "asc" or "desc" Yes Sort direction.
key string No If provided, sorts by an attribute. Syntax:"attr=ATTRIBUTE_NAME" (e.g., "attr=data-value"). If provided, it will sort on the value of the attribute instead of the text content of the cell.

Usage Example

// Sort column 2 in descending order
        sweetTable.sort(2, 'desc');
        
        // Sort column 3 by 'data-date' attribute
        sweetTable.sort(3, 'asc', 'attr=date');

When to Use:

  • When triggering sorts via external buttons.
  • For dynamic sorting (e.g., after filtering data).

5. Summary of Mandatory vs. Optional Methods

Scenario Mandatory Methods Optional Methods
Standard <table> initiate() setCustomParseFunction(), disengage(), sort()
Custom (div, ul, etc.) initiate(), setCustomGetHeadersFunction(), setCustomGetRowsFunction(), setCustomGetTbodyFunction(), setCustomGetCellFromRowFunction() setCustomParseFunction(), disengage(), sort()

6. Best Practices

  1. Always call initiate() after configuration.
  2. Use disengage() when removing tables to avoid memory leaks.
  3. For custom tables, all setCustom... methods are required.
  4. For performance, avoid excessive DOM manipulation inside custom functions.

Conclusion

SweetTable.js provides a flexible, lightweight solution for sorting tables—whether they are standard HTML tables or custom structures. By understanding which methods are mandatory vs. optional, you can easily integrate it into any project.

For better understanding, refer to the test files for real-world implementations. 🚀