user14780746
user14780746

Reputation:

How can I select the closest HTML5 element with JavaScript?

We're integrating analytics into an app, and we're looking to grab the location of an element. In this case, there is no good div that gives a location, so we're trying to grab the nearest element.

Is this possible using .closest? Can I pass an array of tags ['header', 'article', section], and the nearest element that the clicked element is near is selected?

var tabs = Array.from(document.querySelectorAll('.details'));

function handleTabClick(e) {
  var tabNode = e.target;
  tabLabel = tabNode.innerText;
};

tabs.forEach(function(tab) {
  tab.addEventListener('click', handleTabClick);
});

Upvotes: 0

Views: 73

Answers (1)

mplungjan
mplungjan

Reputation: 178350

I would delegate from nearest STATIC html container or from the document

document.addEventListener("click",function(e) {  
  const tgt = e.target;
  if (tgt.tagName==="SECTION" || tgt.closest("section")....) {
   // handle section
  }
  else if (tgt.tagName==="ARTICLE" || tgt.closest("article")....) {) {
   // handle article
  }
})

Upvotes: 1

Related Questions