{hero}

cells().every()

Since: DataTables 1.10.6

Iterate over each selected cell, with the function context set to be the cell in question.

Description

An often used operation with the DataTable API is to perform an operation on a collection of cells - a common action is performed on each cell, such as adding event handlers, updating data, etc. This iteration of the cells can be performed a number of ways in DataTables, each with its own advantages:

This cells().every() method is likely to be the most useful in the majority of cases as it sets the context of the callback function to be the cell() instance for the cell in question (normally a callback in the DataTables API has its context set to be at the top level API hierarchy). In simple terms this means you have the methods such as cell().data() available as this.data() in the callback given to this method.

Consider the following example using each(), which iterates over the cell indexes that have been selected - we are required to get the cell() object for each cell to be able to work with it directly:

table.cells().eq(0).each( function ( index ) {
    var cell = table.cell( index );

    var data = cell.data();
    // ... do something with data(), or cell.node(), etc
} );

Using cells().every() this can be rewritten as:

table.cells().every( function () {
    var data = this.data();
    // ... do something with data(), or this.node(), etc
} );

Although a relatively simple optimisation in terms of code presentation, it can make the code much more readable and intuitive. It is also significantly more performant as of DataTables 2, as API instances do not need to create created every time around the loop.

The other advantage is that the table context is automatically handled - in the first example above where each() is used, the eq() method is used to select the information from the first table in the API's context only, introducing complexity if multiple tables are used. In cells().every() the table context is automatically set to the appropriate table for each cell that has been selected.

Type

function cells().every( fn )

Description:

Iterate over each selected cell

Parameters:
Returns:

DataTables API instance of the selected cells.

Example

Add a class to cells which meet a logical requirement in the source data:

var table = new DataTable('#myTable');

table.cells().every(function () {
	if (this.data() > 50) {
		$(this.node()).addClass('warning');
	}
	else {
		$(this.node()).removeClass('warning');
	}
});

Related

The following options are directly related and may also be useful in your application development.