DEV Community

Discussion on: |DOM| DOM: The World of The DOM

Collapse
 
lifeiscontent profile image
Aaron Reisman

there's also Element.closest which can be super helpful when you need to know if there's an element in the tree above the one you're querying with.

e.g.

function handleClick(event) {
  const header = event.target.closest('.accordion-header');
  const accordion = event.target.closest('.accordion');
  const body = accordion?.closest('.accordion-body');

  if (header) {
   // if I've clicked inside of the header
   // toggle the display of the body of the accordion
    body.hidden = !body.hidden;
  }
}

document.documentElement.addEventListener('click', handleClick, true);
Enter fullscreen mode Exit fullscreen mode