• Usclosest () to return the correct DOM element
  • By Matt Smith
  • The Nuggets translation Project
  • Permanent link to this article: github.com/xitu/gold-m…
  • Translator: LucaslEliane
  • Proofread by: ZYuMing, Moonliujk

Use the Closest () function to get the correct DOM elements

I recently had a problem with the vertical navigation component: the corresponding JavaScript code did not fire when a menu item was clicked. After I have a deeper understanding of this problem, I would like to share the process of solving this problem and the techniques found in this process.

The scenario for this problem is that all menu items have two child elements: an icon and a element as a label, both of which are embedded in the link.

<li>
  <a href="#example" class="toggle">
    <img src="/img/billing.svg" width="20" height="20" alt="">
    <span>Billing</span>
  </a>
  <div id="example">
    <ul>
      <li><a href="/statment/">My Statement</a></li>
      <li><a href="/history/">Pay History</a></li>
    </ul>
  </div>
</li>
Copy the code

There is also a secondary menu in the

element, and I added some JavaScript to control the status of the secondary menu on/off.
document.addEventListener('click'.function (event) {

  // Ensure that the clicked element can be toggled
  if(! event.target.classList.contains('toggle')) {
    return;
  }
  event.preventDefault();

  // Get the element content
  var content = document.querySelector(event.target.hash);
  if(! content) {return;
  }

  // Toggle content on/off
  toggle(content);

}, false);
Copy the code

The toggle method fires a function that checks if the secondary menu has an.IS-Visible CSS class. If the element has this class, the secondary menu is hidden, otherwise the secondary menu is displayed:

var toggle = function (elem, timing) {

  // If the secondary menu is visible, hide it
  if (elem.classList.contains('is-visible')) {
    hide(elem);
    return;
  }

  // Otherwise, display the secondary menu
  show(elem);
};
Copy the code

I want clicking anywhere in the menu item to trigger JavaScript and perform a switch. But if I click on the icon or label child element, the JavaScript doesn’t execute. The reason is that event.target returns the DOM element that was actually clicked on. Clicking on an icon or label returns only the icon or label element.

closest()methods

I need to get the target that triggered the click and return the parent element, not the child element. I used the Closest () approach to the problem. This method iterates the DOM tree, starting with the current element, and returns the closest ancestor that matches the given argument:

let closestElement = Element.closest(selector); 
Copy the code

This code really hit home to me. Closest () and event.target to find and return the parent element (menu item link), regardless of which child element I clicked on (icon or tag) :

if(! event.target.closest('a').classList.contains('toggle')) {
  return;
}

var content = document.querySelector(event.target.closest('a').hash);
Copy the code

Clicking anywhere on the menu item now triggers JavaScript and switches the secondary menu.

You can try it on CODEPEN, and the source code is available.

Hopefully, this tip will help you locate specific DOM elements. The Closest () approach is supported on most major browsers, but Polyfill was required on IE11.

If you need a more in-depth look at this article, I recommend Zell Liew’s article on traversing DOM elements. He describes the method used in this article and some other techniques worth trying.

If you find any mistakes in your translation or other areas that need to be improved, you are welcome to the Nuggets Translation Program to revise and PR your translation, and you can also get the corresponding reward points. The permanent link to this article at the beginning of this article is the MarkDown link to this article on GitHub.


The Nuggets Translation Project is a community that translates quality Internet technical articles from English sharing articles on nuggets. The content covers Android, iOS, front-end, back-end, blockchain, products, design, artificial intelligence and other fields. If you want to see more high-quality translation, please continue to pay attention to the Translation plan of Digging Gold, the official Weibo, Zhihu column.