Accessing table cells in JS

Hi, great that AP9 now has tables.
Is it possible to read out the content of a table cell with JS.

Thanks,
Rolf

Hi Rolf,

You can use the following function to achieve that:

function getTableCellText(tableName, rowIndex, columnIndex) {
  var objectNode = prez.object(tableName).node;
  return $('table tr:nth-child(' + rowIndex + ') td:nth-child(' + columnIndex + ')', objectNode).text();
}

For example, this is the code to get the text in the cell located at row 2, column 3:
getTableCellText('table object name', 2, 3)

Regards,

Excellent, Hang, thank you!
Best, Rolf

1 Like

How would I access the row number of the table to read out all the table values in a for loop?

Thanks, Rolf

If you know the column number, you can reuse the function mentioned above.
For example:

var columnCount = 5;
var rowIndex = 2; // row & column index for getTableCellText start from 1
for (var i = 1; i <= columnCount; ++i)
    console.log(getTableCellText('Table 1', rowIndex, i);

Or, another way is:

var tableName = 'Table 1';
var objectNode = prez.object(tableName).node;
var table = $('table', objectNode)[0];
var rows = table.rows; // array-like collection of rows,  rows[0] -> rows[rows.length - 1]
var row0 = rows[0];
var row0Cells = row0.cells; // array-like collection of cells in row 0
for (var i = 0; i < row0Cells.length; ++i)
    console.log(row0Cells[i].innerText);

Regards,

Thanks, Hang,
I got from this what I needed through

var NrOfRows = $('table', prez.object('Table1').node)[0].rows.length;

I am not much of a programmer. Would it be possible to have something like that as part of a prez.object in the future, along the lines of

var NrOfRows = prez.object('Table1').rows.length

(I don’t know if that counts as a feature request …)

Thanks, Rolf

Thank you, Rolf.

We’ll consider adding it to our To-do list.

Best regards,
Hang