Creating table with javascript and add id and class to each td - javascript

I'm trying to create a chess game in javascript. I created a chessboard and the next step is to add an id's and classes to created td's.
Here is the 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;
for (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 I can simply do this with html, but it's too much code and I belive there is other way to do this.

Here is a solution with plain JavaScript (no jQuery). Put the script just before the closing </body> tag. This does not use document.write which really is to be avoided. Instead the HTML has an empty table with an id attribute, which then is populated through script.
var rows =8;
var cols=8;
var table = document.getElementById('board');
for (var r = 0; r<rows; r++){
var row = table.insertRow(-1);
for (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 a bonus it has the chessboard altering colors, and the id values are running from a1 (bottom-left) to h8 (top-right)

If you can solve this issue by coding the layout directly inside your HTML file, you should definitely do that instead of building it dynamically in JavaScript. This is hugely less error-prone.
That being said, solving this using jQuery is not too hard:
var sideLength = 8;
var table = $('<table>');
$('#root').append(table);
for (var i = 0; i < sideLength; i++) {
var row = $('<tr>');
table.append(row);
for (var j = 0; j < sideLength; j++) {
row.append($('<td>'));
}
}
td {
border: 1px black solid;
width: 10px;
height: 10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='root'></div>

Related

I am trying to create a table of 8x8 squares in HTML using script

I thought maybe doing this with a for loop like that
<table>
<script>
for (var i; i = 0; i < 8; i++) {
document.write("<tr>")
for (var j; j = 0; j < 8; j++) {
document.write("<td></td>")
}
document.write("<tr>")
}
</script>
</table>
This code doesn't seem to work. Please understand that I am not at all fluent in js, so a solution with an explenationn will really help.
document.write would not work as you have tried here, it won't write the <tr> tags at the place you've mentioned either.
You need to modify the DOM, specifically the table element.
Below code, takes a reference of table and appends the 8 rows and 8 cols in it.
document.querySelector("table").innerHTML = new Array(8).fill("<tr>" + new Array(8).fill("<td></td>").join("") + "</tr>").join("");
td {
border: 1px solid;
padding: 5px;
}
<table></table>
PS: This is a basic example to get you started, there are better ways to achieve this. you should look more into DOM Manipulation in JS.
Use DOM manipulation methods and make sure to put <script> right before the closing tag of <body> instead of inside <tabl> , here is a working example:
let table = document.getElementById('table');
for (let i = 0; i < 8; i++) {
let row = document.createElement('TR');
table.appendChild(row);
for (let i = 0; i < 8; i++) {
var cell = document.createElement('TD');
row.appendChild(cell);
}
}
td {
border: 1px solid #333;
padding: 5px;
}
<table id="table"></table>
document.write() will never create a child element inside the <table> element, you can create a child element for a parent with appendChild().
Here an example with pure JavaScript:
for (var i = 0; i < 8; i++) {
var row = document.createElement("tr");
document.getElementById('tbl').appendChild(row).setAttribute("id", 'row_' + i);
for (var j = 0; j < 8; j++) {
var column = document.createElement("td");
document.getElementById('row_' + i).appendChild(column);
}
}
table {
border: 1px solid black;
}
td {
border: 1px solid blue;
padding: 3px;
margin: 2px;
}
<table id='tbl'></table>
Here, the script will create a child <tr> for the <table>, then you can create child <td> for the <tr>.

Generating an html table using javascript

My homework assignment is to generate a checkered html table (aka a chess board) using javascript. I have to use the getElementById and innerHTML properties to do it. I am supposed to generate html strings and add them to the document.
This is what I've written, when i open the page it is empty though, it isn't generating anything at all.
html/script:
<!doctype html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="gameTableStyle.css">
<script>
function showTable() {
var tableDiv = document.getElementById("tableDiv");
tableDiv.innerHTML = genTable();
}
function genTable() {
var html = "";
var i = 0;
var j = 0;
var tClass = "white";
html += "<table>";
for (i = 0; i < 8; i++) {
html += "<tr>";
for (j = 0; j < 8; j++) {
if (i % 2 = 0) {
tClass = "black";
}
else {
tClass = "white";
}
html += "<td>" + "</td>;
}
html += "</tr>";
}
html += "</table>"
return html;
}
</script>
</head>
<body onload="showTable()">
<div id="tableDiv">
</div>
</body>
</html>
css:
.black {
color: black;
}
.white {
color: white;
}
This is my first class on html/javascript so I'm sure there are fancier ways to do this but we are specifically supposed to do it by generating the strings and inserting them in the document. I don't know what I'm doing wrong.

Inline style edited with JavaScript is being ignored

I'm trying to use document.getElementByClassId().style.color to change the color of an element in my HTML document. I can see that it does add an inline style tag to the element but they are seemingly ignored by the browser.
I tried using the !important tag but that changed nothing. Here is my HTML document. I changed my CSS for the elements I want to modify into inline tags but they are ignored as well. Everything else works so far.
Here is my code (I'm a beginner please go easy on me :/).
//Only gets used to make the rows array.
var cells = [];
//Array that contains the entirety of the table element.
var rows = [];
//Random number to be used to color a random cell.
var rand = 0;
//Unique ID number that gets applied to each cell on the gameboard.
var id = 0;
//Calls cellMake.
var makeBoard = function(size) {
cellMake(size);
}
//Adds opening and closing tags at the beginning and end of each string then writes them to the rows array.
var rowMake = function(num) {
for(c = 0; num > c; c++) {
rows[c] = '<tr>' + cells[c] + '</tr>';
}
writeBoard();
}
//Writes cell elements to the cells array based on how many columns the makeBoard function was called for.
var cellMake = function(num) {
for(a = 0; num > a; a++) {
cells[a] = '';
for(b = 0; num > b; b++) {
cells[a] += '<td id="' + id + '" class="pixel">';
id++;
}
}
rowMake(num);
}
//Chooses random pixel from the board and sets its color.
var choosePixel = function() {
rand = Math.round(Math.random() * rows.length * rows.length);
console.log(rand);
document.getElementById(rand).style.color = 'red';
}
//Writes each element of the rows array onto the HTML document.
var writeBoard = function() {
for(d = 0; rows.length > d; d++) {
document.getElementById('gameboard').innerHTML += rows[d];
}
choosePixel();
}
window.onload = function() {
makeBoard(50);
}
<!DOCTYPE html>
<html>
<head>
<title>Can I write JS?</title>
<script src="script.js"></script>
<style>
body {
text-align: center;
background-color: black;
}
#gameboard {
display: inline-block;
margin: 0 auto;
padding-top: 5%;
}
.pixel {
height: 5px;
width: 5px;
}
</style>
</head>
<body>
<table id="gameboard"></table>
</body>
</html>
You have to style the backgroundColor instead of color, because the cells don't contain any text, to which the color would be applied to
//Only gets used to make the rows array.
var cells = [];
//Array that contains the entirety of the table element.
var rows = [];
//Random number to be used to color a random cell.
var rand = 0;
//Unique ID number that gets applied to each cell on the gameboard.
var id = 0;
//Calls cellMake.
var makeBoard = function(size) {
cellMake(size);
}
//Adds opening and closing tags at the beginning and end of each string then writes them to the rows array.
var rowMake = function(num) {
for(c = 0; num > c; c++) {
rows[c] = '<tr>' + cells[c] + '</tr>';
}
writeBoard();
}
//Writes cell elements to the cells array based on how many columns the makeBoard function was called for.
var cellMake = function(num) {
for(a = 0; num > a; a++) {
cells[a] = '';
for(b = 0; num > b; b++) {
cells[a] += '<td id="' + id + '" class="pixel"></td>';
id++;
}
}
rowMake(num);
}
//Chooses random pixel from the board and sets its color.
var choosePixel = function() {
rand = Math.round(Math.random() * rows.length * rows.length);
console.log(rand);
document.getElementById(rand).style.backgroundColor = 'red';
}
//Writes each element of the rows array onto the HTML document.
var writeBoard = function() {
for(d = 0; rows.length > d; d++) {
document.getElementById('gameboard').innerHTML += rows[d];
}
choosePixel();
}
window.onload = function() {
makeBoard(50);
}
<!DOCTYPE html>
<html>
<head>
<title>Can I write JS?</title>
<script src="script.js"></script>
<style>
body {
text-align: center;
background-color: black;
}
#gameboard {
display: inline-block;
margin: 0 auto;
padding-top: 5%;
}
.pixel {
height: 5px;
width: 5px;
}
</style>
</head>
<body>
<table id="gameboard"></table>
</body>
</html>

a dynamic html table using javascript

i am new to js.trying to create a table using js.but codes are not working .what are the faults in this code?it would be a great help if anyone point out the mistakes here.
the css is here
<style>
tr{width:100%;height:100%;border:1px solid black;}
td{height:33%;width:33%;}
.tableShape{
width:300px;
height:300px;
font-size:30px;
text-align:center;
color:red;
}
</style>
js code is here
<!DOCTYPE html>
<html>
<head>
<title>
</title>
</head>
<body>
<script>
var i,j;
var arr=new Array(3);
for(i=0;i<3;i++){
arr[i]=new Array(3);
}
for(i=0;i<3;i++){
for(j=0;j<3;j++){
arr[i][j]=1;
}}
function tabs(){
var s=document.createElement("table");
s.setAttribute('class',"tableshape");
for(i=0;i<3;i++){
var p=s.creatChild("tr");
for(j=0;j<3;j++){
var d=p.creatChild("td");
d.appendTextNode(arr[i][j]);
}
}
document.body.appendChild(s);
}
window.onLoad=tabs;
</script>
</body>
</html>
just change your tabs function like this:
function tabs() {
var s = document.createElement("table");
s.setAttribute('class', "tableshape");
for (var i = 0; i < 3; i++) {
var p = s.insertRow(i);
for (var j = 0; j < 3; j++) {
var d = p.insertCell(j);
d.innerText = arr[i][j];
}
}
document.body.appendChild(s);
}
this is your DEMO
The point is, if you are doing raw javascript like this, since tables have their specific DOM structure, you better create table rows and cells using tbl.insertRow(index) and row.insertCell(index) instead of creating every single node, and append it to the DOM.

How to create a two-dimensional array within a table?

I would like to create a table for a Connect Four game, I would like to do this by setting a two-dimensional 7*6 array and put each array within each cell if that makes sense. I am new to Javascript and do not have lot of knowledge in object orientated programming. I am trying to give each cell a xPosition and yPosition (coordinates, perhaps this could be in their "id") so that the game can check if there is a row or column of Blue or yellow.
Code so far, rough attempt:
function make()
{
var table = document.createElement("table");
for (var i = 0; i < 6; i++)
{
var row = table.inserRow();
for (var j = 0; j < 5; j++)
{
var cell = row.insertCell;
}
document.body.appendChild(table);
}
}
Some really quick solution written with jQuery. I pasted whole html, so you can save it out as html file and open in a browser. You can click on cells to see coordinates (0-based).
<html>
<head>
<title>GRID</title>
<style type="text/css">
table tr td { width: 50px; height: 50px; background-color: silver; border: 1px solid black; }
table tr td.over { background-color: yellow; }
table tr td.active { background-color: red; }
.controls { padding: 20px; }
</style>
</head>
<body>
<div class="controls">
left
top
right
bottom
topleft
topright
bottomright
bottomleft
</div>
<table></table>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
var rows = 6,
cols = 7;
for(var i = 0; i < rows; i++) {
$('table').append('<tr></tr>');
for(var j = 0; j < cols; j++) {
$('table').find('tr').eq(i).append('<td></td>');
$('table').find('tr').eq(i).find('td').eq(j).attr('data-row', i).attr('data-col', j);
}
}
$('table tr td').mouseover(function() {
$(this).addClass('over');
}).mouseout(function() {
$(this).removeClass('over');
}).click(function() {
$(this).addClass('active');
});
$(".controls a").click(function() {
var $active = $("table tr td.active");
if($active.length > 0) {
var move = $.parseJSON($(this).attr('data-move'));
if(move.length >= 2) {
$active.each(function() {
var row = parseInt($(this).attr('data-row')) + move[1],
col = parseInt($(this).attr('data-col')) + move[0];
if(col >= cols) col = cols - 1;
if(col < 0) col = 0;
if(row >= rows) row = rows - 1;
if(row < 0) row = 0;
$(this).removeClass('active');
$('table tr').eq(row).find('td').eq(col).addClass('active');
});
}
}
});
});
</script>
</body>
</html>
Notice that if you change rows and cols variables you can draw bigger grids.
I have added controls div with buttons so you can play with directions. First of all you need to mark element as active, and them you can click to move.
There is one bug (or feature in my opinion) that you can mark multiple fields and move them all at once.
It's good base to start with!

Categories

Resources