Search code examples
javascriptgetelementsbytagname

find cell content highlight different cell in same row


Using the following,

var cells = document.getElementById("test").getElementsByTagName("td");
for (var i = 0; i < cells.length; i++) {
    if (cells[i].innerHTML == "one") {
        cells[i].style.backgroundColor = "red";
    }
}

http://jsfiddle.net/jfriend00/Uubqg/

does anyone know how I can locate any word in a row and have it highlight a specific cell in the same row

take for instance if the word one is found anywhere, it highlights the first cell in that row?


Solution

  • To highlight the first cell, just go back to the parent rows and get the cells:

    var cells = document.getElementById("test").getElementsByTagName("td");
    for (var i = 0; i < cells.length; i++) {
        if (cells[i].innerHTML == "one") {
            var row = cells[i].parentNode;
            row.getElementsByTagName("td")[0].style.backgroundColor = "red";
        }
    }