Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

click event doesn't bubble up on image thats nested in

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading