Find closest ancestor of a clicked element from given array

I’m trying to get the closest ancestor element to a clicked element, from an array of provided elements. When a user clicks on a tab, I need to find out where on the page that tab is.

I have something kind of working, however this script thinks main is the closest tag, when it should be article.

If I put article before main in the array it works just fine, however I wan’t this to work regardless of array order. Any ideas?

// Tab Click
var tabs = Array.from(document.querySelectorAll(''));

function handleTabClick(e) {

  var tabNode =;
  tabLabel = tabNode.innerText;

  const tgt =;
  var location;
  var elements = ['section', 'header', 'main', 'nav', 'article'];

  for (let element of elements) {
    if (tgt.closest(element)) {
      location = element;


tabs.forEach(function(tab) {
  tab.addEventListener('click', handleTabClick);
<main class="company-main-wrapper" id="maincontent">
    <div class="company-grid-row">
      <div class="company-grid-column-two-thirds">
        <div class="company-page-content">
          <div class="block-expander">
            <details class="company-details company-expander" company-polyfilled="true" id="company-details0" open="">
              <summary class="company-details__summary" role="button" aria-controls="company-details__text0" tabindex="0" aria-expanded="true">
                <span class="company-details__summary-text">
                                        sampoe page

9 thoughts on “Find closest ancestor of a clicked element from given array”

Leave a Comment