Reputation: 103
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
Reputation: 3998
Link to CodeSandBox
Errors:
headings
to elements because HTML document have only one unique id.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