DataTables Source Documentation

repository·master·Indexed 21 days ago

https://github.com/datatables/datatablessrc

Source files and developer documentation for DataTables, an HTML table enhancing library providing searching, pagination, and sorting. Includes details on the Api class, the Dom class for DOM manipulation, and the ext namespace for implementing custom row searching, column ordering, and selector extensions.

Tokens
5K
Snippets
20
Records
21
Agent score
74%

What's inside DataTablesSrc

  1. Install DataTables via package managers

    master

    For projects using package managers, DataTables is distributed under the name datatables.net. If you require specific styling for frameworks like Bootstrap or Foundation, you should use the corresponding styling package by adding the appropriate suffix to the package name.

    For detailed instructions on using package managers, refer to the DataTables installation manual.

    # Example for NPM (actual package name is datatables.net)
    npm install datatables.net
  2. Build DataTables from source

    master

    To build DataTables locally for development or modification, ensure your environment meets the following requirements:

    • Bash
    • PHP 7+
    • Node.js 20+

    Follow these steps to clone, install dependencies, build the debug version, and serve the examples locally:

    git clone https://github.com/DataTables/DataTablesSrc.git
    
    cd DataTablesSrc
    
    npm install
    npm run build-debug
    npm serve
  3. Extend DataTables via the `ext` namespace

    master

    The ext object (aliased to jQuery.fn.dataTableExt for legacy compatibility) serves as the central namespace for all DataTables extensions and plugins. Developers use this object to register new capabilities such as custom searching logic, ordering plugins, selector modifiers, and feature plugins. It acts as a collection area where built-in methods and third-party extensions contribute their functionality.

    import ext from 'datatables/js/ext/index';
    
    // Example: Registering a custom search function
    ext.search.push((ctx, cells, rowIdx, data, displayIdx) => {
        // Return true to include the row in search results, false to exclude it
        return data.someValue === 'target';
    });
  4. Use the Dom class for DOM manipulation

    master

    The Dom class provides a chaining interface for selecting and manipulating DOM elements, similar to jQuery. It implements ArrayLike, allowing you to access elements by index or iterate over them. You can create new instances using Dom.create(name) or select existing ones using Dom.select(selector).

    Key capabilities include:

    • Selection: Select by string (CSS selector), Node, Element, or even other Dom instances.
    • Traversal: Navigate the tree using .children(), .parent(), .closest(), .find(), and .siblings().
    • Manipulation: Modify content with .html(), .text(), or .append(); manage classes with .classAdd(), .classRemove(), and .classToggle(); and manage attributes with .attr().
    • Styling: Set CSS properties via .css() or toggle visibility with .show() and .hide().
    import { Dom } from './dom'; // Assuming export
    
    // Select elements
    const myElements = Dom.select('.my-class');
    
    // Chain manipulations
    myElements
      .addClass('active')
      .css({ color: 'red', marginTop: '10px' })
      .html('<strong>Updated Content</strong>');
    
    // Create a new element
    const newDiv = Dom.create('div').text('Hello World');
    document.body.appendChild(newDiv.get()[0]);
  5. Configure DataTables error reporting mode

    master

    The ext.errMode property determines how DataTables reports errors. You can set it to a predefined string or a custom callback function.

    Supported values:

    • 'alert': Uses a standard browser alert.
    • 'throw': Throws a JavaScript error.
    • 'none': Silences all error reporting.
    • (ctx: Context, tn: number | undefined, msg: string) => void: A custom function for handling errors.
    ext.errMode = (ctx, tn, msg) => {
        console.error(`DataTables Error [${tn}]: ${msg}`);
    };
  6. Access the DataTables API

    master

    The DataTables Api class is the primary entry point for interacting with a DataTable instance. It provides a unified interface for manipulating data, controlling table state, and managing UI elements like searching, ordering, and paging. Most interactions are performed by calling methods on the API instance returned when initializing a table or via the $.fn.dataTable() selector.

    // Accessing the API instance (conceptual usage)
    const api = new Api(tableInstance);
    
    // Common patterns involve calling methods directly on the API
    api.search('query').draw();
  7. Perform CSS transitions with transition()

    master

    The transition() method allows for simple CSS animations (like fading). It is not a full animation library but is useful for basic property changes.

    Usage Pattern: To perform a fade-in, first set the initial state (e.g., opacity: 0) and then call .transition().

    Parameters:

    • css: A Record<string, string> of CSS properties to transition to.
    • duration: Transition duration in milliseconds (defaults to 400 if not provided).
    • ease: CSS easing function name (e.g., 'ease-in-out').
    • cb: A callback function executed after the transition completes.

    Note: Global transitions can be disabled via Dom.transitions = false to make changes jump instantly to the end state.

    // Fade in an element
    Dom.select('#message')
      .css({ opacity: '0' })
      .transition({ opacity: '1' }, 500, 'linear', () => {
        console.log('Fade in complete');
      });
  8. Get or set element values with val()

    master

    The val() method is used to retrieve or manipulate the value of elements in the result set (commonly used with <input>, <select>, and <textarea>).

    Getter:

    • Returns the value of the first element in the set.
    • For <select> elements with the multiple attribute, it returns an array of selected option values.

    Setter:

    • Sets the value for all elements in the result set.
    • For <select multiple> elements, you can pass an array of values to select multiple options.
    • Returns this for method chaining.
    // Get value
    const value = dom.val();
    
    // Set value for a single input
    dom.val('new value');
    
    // Set multiple selected values for a <select multiple>
    dom.val(['option1', 'option3']);
  9. Access DataTables core models

    master

    The core data models for DataTables are exported as a default object. This object provides access to the primary abstractions used to represent the state and structure of a table, including Column, Row, Search, and Settings.

    import Model from 'js/model/index';
    
    // Accessing the models
    const columnModel = Model.Column;
    const rowModel = Model.Row;
    const searchModel = Model.Search;
    const settingsModel = Model.Settings;
  10. Implement custom row searching

    master

    The ext.search array allows you to implement comprehensive row-based searching that complements the default type-based searching. Each element in the array is a function called for every row. If the function returns true, the row is included in the search results; if false, it is excluded.

    Function Signature: (ctx: Context, cells: string[] | null, rowIdx: number, data: any, displayIdx: number) => boolean

    ext.search.push((ctx, cells, rowIdx, data, displayIdx) => {
        // Custom logic to decide if row should be visible
        return data.status === 'active';
    });
  11. Use jQuery-like class manipulation aliases

    master

    The Dom prototype provides aliases for class manipulation to provide a jQuery-like experience. While these may not be explicitly typed in TypeScript, they are available on the Dom instance:

    • addClass(className): Adds one or more classes to elements.
    • hasClass(className): Checks if elements have the specified class.
    • removeClass(className): Removes one or more classes from elements.
    // Using aliases on a Dom instance
    dom.addClass('highlighted');
    if (dom.hasClass('active')) {
        dom.removeClass('old-class');
    }