I have a html table with 3 columns and 7rows. When I click on a cell its bg is changed to red. I want to make sure that only one cell from each row is selected. So if I am clicking on a cell from row1, which has already a cell selected, I want the prev cell to be deselected and the new cell selected. I want to know how can I figure out that cells are of same row.
Asked
Active
Viewed 41 times
0
-
Post the code that you have already tried so we could helps. – Zakaria Acharki Jul 08 '16 at 21:16
-
@pracheese you can check `parentElement` property. – Arnial Jul 08 '16 at 21:19
-
`cell.parentNode.cells` will return a list of all the cells in the same row. – Barmar Jul 08 '16 at 21:37
3 Answers
0
If you are using jQuery, in your click handler, do this:
function() {
$(this).closest('tr').find('td').css('backgroundColor', '');
$(this).css('backgroundColor', 'red');
}

Holy Joe
- 146
- 7
0
You can iterate through the rows, and iterate through the cell in an embedded for loop. The solution provided by John Hartsock on this stackoverflow page should allow you to qualify each cell by row and column.
How do I iterate through table rows and cells in javascript?

Community
- 1
- 1

Eric Kristiansen
- 11
- 4
0
Given a table cell, its parentNode
will be the containing row, and table rows have a cells
property that contains a collection of all the cells. So you can loop through that collection.
function selectCell(cell) {
var siblings = cell.parentNode.cells;
for (var i = 0; i < siblings.length; i++) {
if (i != cell.cellIndex) {
siblings[i].style.backgroundColor = normalBGColor;
}
}
cell.style.backgroundColor = highlightBGColor;
}

Barmar
- 741,623
- 53
- 500
- 612
-
is there a similar way to find the column(id or any other identifier) to which the cell belong. – Prachi Verma Jul 08 '16 at 22:56
-
-