Am just trying to assign the same function to a bunch of buttons. I was having trouble referencing the buttons, I ran into "querySelectorAll is not a function" and same for getElementByClass, but with the current code it’s referencing something because the function works, but only on load and not on click.
Here’s the code:
let key;
let text;
let keys;
let alphabet = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"];
for(let i = 0; i < alphabet.length; i++){
key = alphabet[i] + "Key";
text = document.createTextNode(alphabet[i].toUpperCase());
key = document.createElement("button");
key.appendChild(text);
key.classList.add("keys");
keyboard.append(key);
}
keys = document.querySelectorAll(".keys");
keys.onClick = isLetterThere();
}
function isLetterThere(){
console.log("fghjk")
}
3
Answers
In you code
keys = document.querySelectorAll(".keys");
this returns a collection. So you need to iterate this collection and add event to each of the elementYou can do in two ways. Either you can add the
addEventListener
when you create the button.Alternatively you can also add the event using
querySelectorAll
which will return aNodeList
then loop of the collection and add event to itKey’s is an array-like-object, it does not have an
onclick
, nor anonClick
, so assigning the result ofisLetterThere()
will execute the function once and assign its result to the array-like object, instead of your intention of creating a click handler for each letter-button. So, to achieve your goal, you will need to add click handlers to the elements, likekey.addEventListener("click", isLetterThere)