skip to Main Content

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


  1. You have included an extra argument ids in your function, which gets assigned undefined by default, causing this error. Also there’s a typo in .includes:

    document.addEventListener("click", (event) => {
        let whodat = event.target.getAttribute('id');
        let needToKnow = ids.includes(whodat);
        alert(needToKnow);
    });
    
    Login or Signup to reply.
  2. A little more streamlined as you can access most HTML attributes as properties of their DOM representations.

    let ids = ["one", "two", "three", "four", "five"];
    
    document.addEventListener("click", (event) => {
        alert(ids.includes(event.target.id));
    });
    <p id="one">Click me!</p>   <!-- true -->
    <p id="two">Click me!</p>   <!-- true -->
    <p id="three">Click me!</p> <!-- true -->
    <p id="four">Click me!</p>  <!-- true -->
    <p id="five">Click me!</p>  <!-- true -->
    <p id="six">Click me!</p>   <!-- false -->
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search