Gerrit-K
Gerrit-K

Reputation: 1308

how does jQuery.dataTable() hide rows?

I stumbled upon a strange behaviour while using jQuery + dataTables plugin.

Let's say I have the following table:

<table id="myTable">
    <thead>
        <th>col 0</th>
        <th>col 1</th>
    </thead>
    <tbody>
        <tr>
            <td><input type="checkbox" /></td>
            ...
        </tr>
        ...
    </tbody>
</table>

I call $('#myTable').dataTable({...}); on document.ready and want to get all rows that have checked inputs when I click a button (even if they are not on the current page of the table).

To get all rows (including unchecked) I use $('#myTable').dataTable().fnGetNodes() (API-Link) which returns an array with all those tr-nodes. After that I use this array to construct a jQuery-object:

var nodearray = $('#myTable').dataTable().fnGetNodes();
var trs = $(nodearray);

Here comes the part I don't understand. I tried two ways to get all checked nodes but the results were different:

// returns all rows correctly (including invisible rows from other pages)
trs.find('td input:checked').closest('tr'); 

// return only rows from the current page
trs.has('td input:checked');

What does the DataTables-plugin do to hide rows so that jQuery.has() doesn't find them and why does jQuery.find() still work though?

PS: I created a simple fiddle here

Upvotes: 4

Views: 1625

Answers (1)

plalx
plalx

Reputation: 43748

If we inspect the DOM, we can see that only the current page elements are part of the DOM, so the others are hidden simply because they aren't in the DOM and resides in memory only.

However for the disrepancy issue, it seems to only occur with jQuery versions prior to 1.8.x so it's probably a bug in the library that got fixed.

Here's a test case that shows the has method doesn't work for in-memory elements in versions below 1.8.x:

console.log($('<div><span></span></div>').has('span').length); //0

EDIT: It was a bug and I found the ticket: http://bugs.jquery.com/ticket/11543

Upvotes: 3

Related Questions