xiang
xiang

Reputation: 103

How to apply EventListener to each element of an array?

I am trying to apply onclick eventlistener on each of the elements in an array. How can I do that? I tried using querySelectorAll but it doesn't work. You can check the code here: https://codesandbox.io/s/unruffled-ishizaka-4g9uq?file=/src/App.js:93-229. Thanks in advance for the help.

let head = document.querySelectorAll("heading");
    for (let i of head)
      i.addEventListener("click", function h() {
        let a = document.getElementById("subheading");
        a.style.display = "none";
      }); 

Upvotes: 0

Views: 127

Answers (1)

Ferin Patel
Ferin Patel

Reputation: 3998

Link to CodeSandBox

Errors:

  1. You can need to give class-names headings to elements because HTML document have only one unique id.
  2. While looping over element in useEffect you need to find const a = i.querySelector(".subheading") like this.

Link to CodeSandBox

import "./styles.css";
import { useEffect } from "react";

export default function App() {
  const headings = ["1. Heading", "2. Heading", "3. Heading"];
  const subheadings = ["1. Subheading", "2. Subheading", "3. Subheading"];

  useEffect(() => {
    const head = document.querySelectorAll(".heading");

    head.forEach((i) => {
      i.addEventListener("click", function () {
        const a = i.querySelector(".subheading");
        a.style.display = "none";
      });
    });
  }, []);

  return (
    <div className="App">
      <div>
        {headings.map((val, index) => (
          <li key={index} style={{ listStyle: "none" }} className="heading">
            <a href="#">{val}</a>
            <ul className="subheading">
              {subheadings.map((val, index2) => (
                <li key={index2} style={{ listStyle: "none" }}>
                  <a href="#">{val}</a>
                </li>
              ))}
            </ul>
          </li>
        ))}
      </div>
    </div>
  );
}

Link to CodeSandBox

Upvotes: 1

Related Questions