jquery - Creating table with javascript and add id and class to each td -
i'm trying create chess game in javascript. created chessboard , next step add id's , classes created td's.
here code:
<html> <head> <title> play chess! </title> <meta charset="utf-8"> <link rel='stylesheet' href='css/styles.scss' type='text/css'/> </head> <body> <script> var table =''; var rows =8; var cols=8; (var r = 0; r<rows;r++){ table +='<tr>'; for(var c=0;c<cols;c++){ table+='<td>' +''+'</td>'; } table+='</tr>'; } document.write("<table border=1>"+table+'</table>'); </script> </body> </html>
i know can html, it's code , belive there other way this.
here solution plain javascript (no jquery). put script before closing </body>
tag. not use document.write
avoided. instead html has empty table id
attribute, populated through script.
var rows =8; var cols=8; var table = document.getelementbyid('board'); (var r = 0; r<rows; r++){ var row = table.insertrow(-1); (var c = 0; c<cols; c++){ var cell = row.insertcell(-1); cell.setattribute('id', 'abcdefgh'.charat(c) + (rows-r)); cell.setattribute('class', 'cell ' + ((c+r) % 2 ? 'odd' : 'even')); } }
table { border-spacing: 0; border-collapse: collapse; } .cell { width: 20px; height: 20px; } .odd { background-color: brown } .even { background-color: pink }
<table id="board"></table>
as bonus has chessboard altering colors, , id
values running a1
(bottom-left) h8
(top-right)
Comments
Post a Comment