Jack
Jack

Reputation: 99

Pushing results to array

<tr>
    <td>1st</td>
    <td class="result horse1"></td>
</tr>
<tr>
    <td>2nd</td>
    <td class="result horse2"></td>
</tr>
<tr>
    <td>3rd</td>
    <td class="result horse3"></td>
</tr>
<tr>
    <td>4th</td>
    <td class="result horse4"></td>
</tr>

This is a game in javascript and when the horse crosses the line it will execute the this.finish function.

It will get the results and display them in a table by changing classes to include the ID. This works fine but when I then push the ID into the array it will only store two of the id's before throwing an error.

if (horse.lap == laps && horse.x == horse.startX + 5) {
    horse.finish();
}   

this.finish = function() {
    this.element.className = 'horse standRight';
    var table = document.getElementsByClassName('result');
    table[results.length].className = id;
    results.push(id);
    console.log(results);
  }

var results = [];

When displaying the results in the table, it also skip the 2nd row and place an id in the third row?

This is the errorhors3, crossed first, horse1 second then break.

Upvotes: 0

Views: 401

Answers (1)

Vasan
Vasan

Reputation: 4956

As mentioned the comments, you're replacing the entire classname with id, so the "result" in the className is gone too.

You can instead replace the horse ID part alone with the new one i.e.

table[results.length].className = "result " + id;

OR

var currentClass = table[results.length].className;
table[results.length].className = currentClass.replace(/horse[0-9]/,id);

There are more ways to do this too, including splitting the classname by space etc.

Upvotes: 1

Related Questions