子元素与后代元素_如何检查一个元素是否是另一个元素的后代

子元素与后代元素

I had the need to find out of an element I got via a click event was a descendant of a particular parent element.

我需要找出通过click事件获得的元素是特定父元素的后代。

I assigned an id to that parent, and I checked if the clicked element belonged to its child elements using this loop:

我为该父对象分配了一个id ,并使用此循环检查了clicked元素是否属于其子元素:

const isDescendant = (el, parentId) => {
  let isChild = false

  if (el.id === parentId) { //is this the element itself?
    isChild = true
  }

  while (el = el.parentNode) {
    if (el.id == parentId) {
      isChild = true
    }
  }
  
  return isChild
}

document.addEventListener('click', event => {
  const parentId = 'mycontainer'

  if (isDescendant(event.target, parentId)) {
    //it is a descendant, handle this case here
  } else {
    //it's not a descendant, handle this case here
  }
})

In the while loop we use the assignment operator = to iterate until there’s no parent node anymore, in that case el.parentNode returns null and the while loop ends.

在while循环中,我们使用赋值运算符=进行迭代,直到没有父节点为止,在这种情况下, el.parentNode返回null ,而while循环结束。

It’s a way to go “up” in the elements tree until it finishes.

这是在元素树中“向上”直至完成的一种方法。

翻译自: https://flaviocopes.com/how-to-check-element-descendant/

子元素与后代元素

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值