let body = document.querySelector("body");
let container = document.querySelector("#container");
//Accessing HTML Elements
let inputArray = [];
for (let element = 0; element < 30; element ) {
space = document.createElement("input");
container.appendChild(space);
space.setAttribute("id", element);
space.classList.add("square");
inputArray.push(space);
}
//For loop that creates a grid of squares and adds each square to an array
document.onkeydown = event => {
if (event.keyCode === 37) {
for (let i = 0; i < 31; i ) {
inputArray[i].value = "";
}
}
}
//When the left arrow key is pressed, the text in every square disappears
CodePudding user response:
I do not see the problem. (Apart from the error Uncaught TypeError: Cannot set properties of undefined (setting 'value')
: you using loop i<31
to the clear, but you only use i<30
to the create).
And a little mistake: you do not define the space
variable (I recommend to use let
).
CodePudding user response:
If I understood your question correctly?
const container = document.querySelector('#container')
const inputArray = Array.from(({length:30}),(e,i)=>
{
let space = container.appendChild( document.createElement('input') )
space.id =
space.placeholder = i
space.className = 'square'
})
container.onkeydown = evt =>
{
if (evt.key === 'ArrowLeft' && evt.target.matches('input'))
{
evt.target.value = '';
console.clear()
console.log(`element.id = "${ evt.target.id }"`)
}
}
.square {
margin : .2em;
width : 6em;
}
<div id="container"></div>