As a learning experiment, I’ve created a page that includes elements with a certain set of ids. The objective is to perform an action if the element clicked on has an id in that set. The code is in a script collect.js
. The problem is that the line let needToKnow = ids.incudes(whodat);
throws the error:
TypeError: Cannot read properties of undefined (reading 'incudes')
at HTMLDocument.<anonymous> (collect.js:7:30)
The goal is to render a modal if needToKnow
is true. But how do I get past the line that fails?
window.onload = (function () {
const images = document.querySelectorAll("img");
const ids = Array.from(images, (image) => image.id);
document.addEventListener("click", (event, ids) => {
let whodat = event.target.getAttribute('id');
let needToKnow = ids.incudes(whodat); // fails here
alert(needToKnow);
});
});
2
Answers
You have included an extra argument
ids
in your function, which gets assignedundefined
by default, causing this error. Also there’s a typo in.includes
:A little more streamlined as you can access most HTML attributes as properties of their DOM representations.