[英]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.我们正在将分析集成到应用程序中,并希望获取元素的location
。 In this case, there is no good div that gives a location, so we're trying to grab the nearest element.在这种情况下,没有给出位置的好 div,所以我们试图抓取最近的元素。
Is this possible using .closest
?这可以使用.closest
吗? Can I pass an array of tags ['header', 'article', section]
, and the nearest element that the clicked element is near is selected?我可以传递一个标签数组['header', 'article', section]
,并选择单击元素附近的最近元素吗?
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); });
I would delegate from nearest STATIC html container or from the document我将从最近的 STATIC html 容器或文档中委托
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
}
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.