towi_parallelism
towi_parallelism

Reputation: 1471

Get elements inside a jQuery DataTable

I want to access elements created dynamically in a jQuery DataTable. Consider the code below:

$( document ).ready(function() {
  var tableref = $('#myTable').DataTable({ "pageLength": 10 });
  for (var k=0; k<15; k++) {
    tableref.row.add(['<div id="myDiv' + k + '">'+k+'</div>']).draw();
    console.log(document.getElementById('myDiv'+k));
  }

});

Since the page size is set to 10, I can only access the first 10 divs. You can see that output of the console for the next 5 elements is null.

fiddle demo

Why does it happen? and how can I resolve this problem?

Upvotes: 2

Views: 6043

Answers (2)

CMedina
CMedina

Reputation: 4222

If you want get all elements of your table you can use rows().nodes(), returns a list of tr elements that have been generated.

read for more information http://datatables.net/forums/discussion/7454/fngetnodes-only-returning-visible-nodes

In your Example ....

$( document ).ready(function() {
   var tableref = $('#myTable').DataTable({ "pageLength": 10 });
   for (var k=0; k<15; k++) {
      tableref.row.add(['<div id="myDiv' + k + '">'+k+'</div>']).draw();
      //console.log(document.getElementById('myDiv'+k));//Return 10 divs
   }

  var aTR = tableref.rows().nodes();

  for (var i = 0; i < aTR.length; i++) {

       console.log($(aTR[i]).find('div')); //return 20 divs

  }

});

Result: https://jsfiddle.net/cmedina/7kfmyw6x/22/

Upvotes: 1

Richard Mosselveld
Richard Mosselveld

Reputation: 712

If you want to access the data of a datatables object, you should not iterate over the rows, but over the data property.

For reference, check out this page: https://datatables.net/reference/api/data()

Upvotes: 1

Related Questions