when i click on the image it doesnt bubble up to the parent which does have the "questions" class and make the if condition true, isnt it supposed to work that way?
document.addEventListener('click', function(event){
if(event.target.classList.contains('questions')){
const answers = event.target.nextElementSibling;
answers.style.display = answers.style.display === "block"? "none" : "block";
}
else{
document.querySelectorAll('dd').forEach((dd)=>dd.style.display= "none")
}
});
<div class="faq-item">
<dt class="questions">qstn
<img class="questionsArrow" src="https://placehold.co/50?text=%3C%3E%3C" >
</dt>
<dd class="answers">answr</dd>
</div>
>Solution :
It does bubble up to the element with the questions class, but that element isn’t event.target, the one you’re testing. That’s the img (mdn: target). The element with the questions class is event.target‘s parent. The best way to get it is probably the closest method (in case you change the HTML slightly):
document.addEventListener("click", function (event) {
const questions = event.target.closest(".questions");
if (questions) {
const answers = questions.nextElementSibling;
answers.style.display = answers.style.display === "block" ? "none" : "block";
} else {
document.querySelectorAll("dd").forEach((dd) => (dd.style.display = "none"));
}
});
The closest method accepts a CSS selector and finds the first element matching that selector, starting with the one you call it on, then if that doesn’t match trying its parent, and if the parent doesn’t match, the parent’s parent, etc.
You could make the code even less