I have a dynamically created table and have given each cell row and column attributes to give them numbers between 0-9(10X10 table) called data-x, data-y. I want to select a random data-x, and data-y (that has a class of empty) and then assign that cell a another class. I know that I could do it in an easier way by randomly selecting just the cell itself but for some reason it needs to be done this way.
I made variables for random numbers between 0-9 but don't really know how they can connect to my data-x/y in order to do the above.
Could anyone give me advice on the simplest way to do this?
Thanks
$( document ).ready(function() {
var body = document.getElementsByTagName("body")[0];
var table = document.createElement('TABLE');
var tblB = document.createElement('TBODY');
table.appendChild(tblB);
var num = [1];
for (var i = 0; i <10; i++) {
var tr = document.createElement('TR');
tblB.appendChild(tr);
$(tr).attr('data-x', i)
for (var j=0; j<10; j++) {
var td = document.createElement('TD');
tr.appendChild(td);
td.append(num++);
$(td).attr('data-y', j);
}
}
body.appendChild(table);
var randomRow = Math.floor(Math.random() * 9);
var randomCol = Math.floor(Math.random() * 9);
//How to select a <td> of random data-x,data-y with these randomRow and randomCol numbers
//$(td).???
console.log(randomCol, randomRow);
//Give all cells a class of empty to start
$("td").addClass('empty');
var obs = 0;
while (obs <= 10) {
//Find random row and column that has class empty, add Class(dimmed) to that random row and column (eg. 2 1)
// var randomRow = Math.floor(Math.random() * 9);
// var randomCol = Math.floor(Math.random() * 9);
// console.log(randomNum + randomCol);
obs++
}
})
table td {
padding: 25px;
border: 5px solid red;
}
table {
margin: auto;
}
.dimmed {
background: black;
}
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="style.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="script.js"></script>
</head>
<body bgcolor="lightblue">
<center>
<h1>Create table in a dynamic way using javascript</h1>
</center>
<CENTER>
<div id=TBL></div>
</CENTER>
</body>
</html>