Dan Zawadzki Dan Zawadzki - 1 year ago 88
Javascript Question

Assigning values to html elements and reading it

i'm trying to make tic tac toe game, basing just on html,css,pure js. I have already base of game (there is one bug), but i have problem to detect once someone wins. I've decided to use MagicSquare algorithm, but i don't have idea how to attach value to each td element. Here you can find, what i have at this moment. I'm trying to make something like

player += Number(target.value);
and once one of the players collect 15, then i stop game and display message. Ofc, this doesn't work now, so can you advice me some good idea how to assign values with td elements and later read it via js, once player generate click event?


<table class="gameArea" onclick="myFunction(event)">
<td value=4></td>
<td value="9"></td>
<td value="2"></td>
<td value="3"></td>
<td value="5"></td>
<td value="7"></td>
<td value="8"></td>
<td value="1"></td>
<td value="6"></td>


var player1 = 0,
player2 = 0,
round = 0;

function myFunction(event) {
var target = event.target;
//target.className += "x";

if(hasClass(target, "x") || hasClass(target, "y") ){

if(round === 1){
target.className += "x";
player1 += Number(target.value);
round = 0;
} else {
target.className += "y";
round = 1;
player2 += Number(target.value);
console.log("Player 2: " + player2);


function hasClass( elem, klass ) {
return (" " + elem.className + " " ).indexOf( " "+klass+" " ) > -1;

Answer Source

Change your HTML to use data attributes, like so:

<td data-value="3"></td>

You can then read the value, like so:

player1 += parseInt(target.dataset.value, 10);

More info on MDN here.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download