SDHKSV
SDHKSV

Reputation: 37

onclick td element, only this one will change

I have an issue with onclick events. I have a 3*3 table and when I click on a td element I want only this one to be change. The code :

var CaseID = new Array(1, 2, 3, 4, 5, 6, 7, 8, 9);
var table = document.createElement("table");
for (a = 0; a < 3; a++) {
    var tr = document.createElement("tr");
    for (b = 0; b < 3; b++) {
        var td = document.createElement("td");
        
        td.onclick = function() {
    // here I want to change backgroundColor into red, but only for the one I pressed
        };
        
        tr.appendChild(td);
    }
    table.appendChild(tr);
}
document.body.appendChild(table);

for (c = 0; c < CaseID.length; c++) {
    document.getElementsByTagName("td")[c].id = CaseID[c];
}
table {
  border-collapse:collapse;
}

tr, td {
  height:50px;
  width:50px;
  border:1px #000 solid;
}

Upvotes: 1

Views: 46

Answers (1)

Chris Forrence
Chris Forrence

Reputation: 10084

You can just set its style property's backgroundColor, as shown below. Within that onclick function, this refers to the element.

var CaseID = new Array(1, 2, 3, 4, 5, 6, 7, 8, 9);
var table = document.createElement("table");
for (a = 0; a < 3; a++) {
    var tr = document.createElement("tr");
    for (b = 0; b < 3; b++) {
        var td = document.createElement("td");
        
        td.onclick = function() {
            this.style.backgroundColor = 'red';
        };
        
        tr.appendChild(td);
    }
    table.appendChild(tr);
}
document.body.appendChild(table);

for (c = 0; c < CaseID.length; c++) {
    document.getElementsByTagName("td")[c].id = CaseID[c];
}
table {
  border-collapse:collapse;
}

tr, td {
  height:50px;
  width:50px;
  border:1px #000 solid;
}

Upvotes: 1

Related Questions