Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loop through elements in a HTML table

I am learning Javascript, in a school assignment we have to by using a loop count how many games was made in 2014.

It does not return anything in the console, where have I gone wrong?

var allGames = document.getElementsByTagName('td');
var array = Array.prototype.slice.call(allGames, 0)
var games14 = 0;
for (var i = 0; i < array.length; ++i) {
  if (array[i] == 2014) {
    games14++;
    console.log(games14)
  }
}
<table id="games">
  <thead>
    <tr>
      <th>Titel</th>
      <th>Genre</th>
      <th>Årstal</th>
    </tr>
  </thead>
  <tbody id="games_tbody">
    <tr class="horror">
      <td class="title">Outlast</td>
      <td>Horror</td>
      <td>2013</td>
    </tr>
    <tr class="rpg">
      <td class="title">Dragon Age: Inquisition</td>
      <td>Role-playing Game</td>
      <td>2014</td>
    </tr>
    <tr class="rpg">
      <td class="title">Skyrim</td>
      <td>Role-playing Game</td>
      <td>2011</td>
    </tr>
    <tr class="horror">
      <td class="title">Amnesia: The Dark Descent</td>
      <td>Horror</td>
      <td>2010</td>
    </tr>
    <tr class="simulator">
      <td class="title">Scania Truck Driving Simulator</td>
      <td>Simulator</td>
      <td>2012</td>
    </tr>
    <tr class="horror">
      <td class="title">Five Nights at Freddy’s</td>
      <td>Horror</td>
      <td>2014</td>
    </tr>
    <tr class="simulator">
      <td class="title">Sims 4</td>
      <td>Simulator</td>
      <td>2014</td>
    </tr>
    <tr class="rts" id="last">
      <td class="title">Warcraft III: Reign of Chaos</td>
      <td>Real-time Strategy</td>
      <td>2002</td>
    </tr>
  </tbody>
</table>
like image 755
Julie Bang Avatar asked Sep 16 '26 07:09

Julie Bang


1 Answers

You need to check for its text:

var allGames = document.getElementsByTagName('td');
...
 if (array[i].innerHTML == '2014') {

OR,

if(array[i].innerText == '2014' || array[i].textContent == '2014'){
like image 83
Bhojendra Rauniyar Avatar answered Sep 18 '26 21:09

Bhojendra Rauniyar