niclake niclake - 3 months ago 17
Javascript Question

DataTables - Process rows with specific cell class

I'm attempting to loop through a DataTable, and only process rows that contain a cell with a class of "success". I'm having trouble getting the syntax properly; can anyone assist?

Here's what I have so far (that isn't working):

for(i=0; i<myDataTable.rows()[0].length; i++) {
if(myDataTable.rows(i).data()[0] != "" && myDataTable.rows(i).data()[0].child('td').hasClass('success')) {
<process stuff>
}
}


Any suggestions?

Answer

You can do this with the row().node() DataTables API call in combination with the .find() jQuery function:

for(i=0; i<myDataTable.rows().length; i++) {
    if(myDataTable.row(i).data()[0] != "" // <-- See Note about this part 
      && $(myDataTable.row(i).node()).find('td.success').length) {
        //process stuff
    }
}

This modification of your code snippet will use the node() call, which gets the <tr> element of the row found by myDataTable.row(i). Then, we can use the find() method to check if any (it would be different if you only cared about a specific column) of the <td> in that <tr> have the success class.

Note

Your code has myDataTable.row(i).data()[0] != "". This checks that the first column of the row is not the empty string. If you want that to be part of the condition for processing, leave it in, but I'm not sure since you didn't mention that in the question.

Also note that for a single row, you should use row() not rows().