this is a codepen demo at here and you try to click on the canvas and is able to undo and clear the grid. The problem I am trying to solve is I want to place some numbers (in black) in the red square. For example, when you click on the grid, first red dot will appear and inside labelled as 1 and the second will be labelled 2 and so on and if the dots overlap, it will just show the original number(not a new number). I have tried to use the code below:
var elements = document.getElementsByClassName('red-dot');
elements.innerHTML = 'Testing here';
Thank you for reading :)
CodePudding user response:
This should do it:
- accessing elements by classname needs to be by index e.g
document.getElementsByClassName(.red-dot)[0]
will access the first element with the classname red-dot - in the codepen you used style top and left to position the red-dot, so i used it as skip if taken by an element of the same class name
The rest is self explanatory.
var elements = document.getElementsByClassName('red-dot');
var eLength = elements.length;
const dValue = parseInt(eLength) 1;
let isTaken = false;
// check if dot number is taken
for (let d=0;d<eLength;d ) {
let top = elements[d].style.top;
let left = elements[d].style.left;
if (top == newDot.style.top && left == newDot.style.left) {
isTaken = true;
}
}
if (!isTaken) {
newDot.dataset['dvalue'] = dValue;
newDot.innerHTML = newDot.dataset.dvalue;
} else {
newDot.style.backgroundColor = 'transparent';
}
document.body.appendChild(newDot);