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

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

  1. My brother recommended I may like this web site. He was once totally right.
    This post actually made my day. You can not believe just how much time I had spent for this information! Thanks!

  2. Very good blog! Do you have any tips for aspiring writers?
    I’m planning to start my own website soon but I’m a little
    lost on everything. Would you recommend starting with a free platform like
    Wordpress or go for a paid option? There are so many choices out
    there that I’m completely confused .. Any recommendations?
    Many thanks!