0

I'm having an issue with the addeventlistener and "click", I launch my web page but the JS click doesn't seem to execute, I looked around and can't find where the error is, maybe someone can help :-) Also I'd like to dinamically display the number of green cells on the page, maybe someone can give me a clue on this too as a bonus :-) Here's my code:

CSS

.green { background: green; color: white; }
.white { background: white; color: black; }

#sales-list { border: 1px solid black; }
td { padding: 10px; border: 1px solid black; }

HTML

<head>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
<title>Untitled 3</title>
<link rel="stylesheet" type="text/css" href="Untitled_1.css"/>
</head>
<body>
<script type="text/javascript">
var cells = document.querySelectorAll("td");
for (var i = 0; i < cells.length; i++) {
cells[i].addEventListener("click", function() {
this.className= this.className == "white" ? "green" : "white";
});
}
document.write("Number of green cells: ")
</script>

<table id="sales-list">
<tr>
<td class="white">TEST1</td>
<td class="white">TEST2</td>
<td class="white">TEST3</td>
</tr>
</table>
</body>
</html>
Voilier
  • 43
  • 6

1 Answers1

-1

Your code seems to work perfectly I've added a way to show the count here below:

var cells = document.querySelectorAll("td");
var counts = {white: 3 , green: 0}
for (var i = 0; i < cells.length; i++) {
cells[i].addEventListener("click", function() {
counts[this.className] = counts[this.className] - 1;
this.className= this.className == "white" ? "green" : "white";
counts[this.className] = counts[this.className] + 1;
console.log(counts);
document.getElementById("showCount").innerHTML = JSON.stringify(counts);
});
}
.green { background: green; color: white; }
.white { background: white; color: black; }

#sales-list { border: 1px solid black; }
td { padding: 10px; border: 1px solid black; }
<head>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
<title>Untitled 3</title>
<link rel="stylesheet" type="text/css" href="Untitled_1.css"/>
</head>
<body>

<table id="sales-list">
<tr>
<td class="white">TEST1</td>
<td class="white">TEST2</td>
<td class="white">TEST3</td>
</tr>
</table>
<div id="showCount"></div>
</body>
</html>
Black Mamba
  • 13,632
  • 6
  • 82
  • 105
  • My code was right but wasn't working because the JS code must be added after my table in HTML. Thar resolved my issue and thanks again to @Black Mamba – Voilier Feb 18 '19 at 13:19