0

Fefering to this example: Changing table cell contents.

How is it possible to change a table cell if their is more then 1 column and no content in the cell.

For example change the 3rd cell in the 2nd column?

<table width="200" border="1">
  <tr>
    <th scope="col">Daten 1</th>
    <th scope="col">Daten 2</th>
    <th scope="col">Daten 3</th>
  </tr>
  <tr>
    <td id="A1">1</td>
    <td id="B1">1</td>
    <td id="C1">&nbsp;</td>
  </tr>
  <tr>
    <td id="A2">2</td>
    <td id="B2">2</td>
    <td id="C2">&nbsp;</td>
  </tr>
  <tr>
    <td id="A3">3</td>
    <td id="B3">3</td>
    <td id="C3">&nbsp;</td>
  </tr>
  <tr>
    <td id="A4">4</td>
    <td id="B4">4</td>
    <td id="C4">&nbsp;</td>
  </tr>
</table>
Community
  • 1
  • 1
The Masta
  • 837
  • 3
  • 9
  • 17

4 Answers4

0

You're looking for the :nth-child selector. Much like the CSS selector it's based on, nth-child(i) takes 1-based indexes.

$('table tr:nth-child(2) td:nth-child(3)').html('changed');

Here is a Fiddle demonstrating it.

Soviut
  • 88,194
  • 49
  • 192
  • 260
0

To Select 3rd cell in 2nd column this means You have to select 3rd row first and then pick its second column. Try this jquery selector on your table

$('#data tr:nth-child(3) td::nth-child(2))

or even better

$('#data').find('tr:nth-child(3)').find('td::nth-child(2)')

Even This might not be the best way to get the table cell.

Suggestion: If you can give some id based on their index to each table cell, then its easy to compute the id and use $('#cellId_23').

Each cell will have its unique ID. For example: Cell(1,1) can have id like cell_11 and Cell(1,2) will have cell_12 and so on.

This will be much better performant than above two selectors.

Sachin Jain
  • 21,353
  • 33
  • 103
  • 168
0

Also you can use the eq() method to find the td starting from 0 index.

var value = $('#table_id').find("td").eq(5).html();

0

something like,

jQuery(document).ready(function(){
    var t = document.getElementById('data');
    jQuery(t.rows[1].cells[2]).text('1st row last C'); 
    jQuery(t.rows[2].cells[2]).text('2nd row last C'); 

});

Live Demo

Jobin
  • 8,238
  • 1
  • 33
  • 52