pracheese pracheese - 4 months ago 16
HTML Question

how can I figure out that cells are of same row

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.

Answer

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;
}
Comments