1

How come this works:

    alert(document.getElementById("tableId").rows[7].cells[7].innerHTML);

But not this:

    alert($("#tableId").rows[7].cells[7].innerHTML);

For context, I had used .append to add in cells to the table, and I want to be able to manipulate each cell further in the future (such as using .data, which is why I want to use jQuery.

Alternatively, are there other ways to access the individual cells in the table? Thank you.

RawMeat
  • 23
  • 2

2 Answers2

0

The former works because getElementById() returns an HTMLTableElement object which has the rows property. The latter uses a jQuery object which does not have the rows property, so you get an error.

You could solve this by retrieving the underlying Element from the jQuery object in one of two ways:

console.log($("#tableId")[0].rows[7].cells[7].innerHTML); // access by index
console.log($("#tableId").get(0).rows[7].cells[7].innerHTML); // get(0)

Alternatively you could use jQuery selectors to select the cell you want directly:

let html = $('#tableId tr:eq(7) td:eq(7)').html();

For context, I had used .append to add in cells to the table, and I want to be able to manipulate each cell further in the future

If this is the case you can save a reference to the content you add so that you can use it again without having to perform a DOM access operation. In pseudo-code it would look something like this:

let $content = $('<tr><td>Foo</td></tr').appendTo('#tableId');

// in some other function later in the page execution...
$content.find('td').text('bar').data('lorem', 'ipsum');
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
  • Could you explain why you put a [0] after $("#tableId")? What exactly is it accessing? – RawMeat May 07 '20 at 09:54
  • It's accessing the jQuery object and retrieving the original Element object from which it was created. [Here's a better explanation](https://stackoverflow.com/q/32783869/519413) – Rory McCrossan May 07 '20 at 09:59
0

If you are looking to loop over each row

$('#tableId tr').each(function() {
  if (!this.rowIndex) return; // to skip first row if you have heading
    console.log(this.cells[0].innerHTML);
});
Tranquillity
  • 237
  • 2
  • 9