Senario: To be able to access a particular cell <td></td> on one of the rows in HTML table.
Using jQuery we can easily access a particular row and then target a cell of a HTML table easily by using the eq() traversal filter method and the :nt-child() pseudo class methods available.
Let us say we are having the following table (Where firs value represents row, 2nd value cell)
0,0 | 0,1 | 0,2 | 0,3 | 0,4 |
1,0 | 1,1 | 1,2 | 1,3 | 1,4 |
2,1 | 2,1 | 2,2 | 2,3 | 2,4 |
3,3 | 3,1 | 3,2 | 3,3 | 3,4 |
To access or select any row using jQuery we can use (assuming there is only one table):
$("tr").eq(n) // where n is supposed to be a number between 0 and nth row.
So to set background color of a row we can use:
$("tr").eq(2).css({"background": "gray"});
0,0 | 0,1 | 0,2 | 0,3 | 0,4 |
1,0 | 1,1 | 1,2 | 1,3 | 1,4 |
2,1 | 2,1 | 2,2 | 2,3 | 2,4 |
3,3 | 3,1 | 3,2 | 3,3 | 3,4 |
Since now we can access the row, we can now target the cell in that row by using the :nth-child() selector, which selects the nth child of the enveloping element.
We know that $("tr").eq(n) will select the nth row, now if we add td inside the main selector just like css stype with the nth-child selector, we can pin point a particular cell.
$("tr td:nth-child(x)").eq(y) // here we can replace the y with row number and x with cell number counting from 1.
So to select the 4th cell in 3rd row and set its background yellow, we can use:
$("tr td:nth-child(4)").eq(2).css({"background": "yellow"});
0,0 | 0,1 | 0,2 | 0,3 | 0,4 |
1,0 | 1,1 | 1,2 | 1,3 | 1,4 |
2,1 | 2,1 | 2,2 | 2,3 | 2,4 |
3,3 | 3,1 | 3,2 | 3,3 | 3,4 |
That all!!!
Add new comment