如何通过#myselector元素,仅用类选择器选中祖先#tryingtoselectthis
如何通过#myselector用类选择器选中祖先#tryingtoselectthis?
你遇到的问题核心在于closest()会优先匹配元素自身——因为#myselector本身就带有.card类,所以直接调用closest(".card")会返回它自己,而不是你目标的#tryingtoselectthis。这里给你两种靠谱的解决方案:
方法一:先取父元素再调用closest
先通过parentElement跳到#myselector的直接父节点,再调用closest(".card"),就能精准定位到上层的#tryingtoselectthis:
console.log(document.querySelector("#myselector").parentElement.closest(".card"));
方法二:结合:scope伪类排除自身
:scope代表当前元素的作用域,用.card:not(:scope)作为选择器,让closest跳过自身,直接匹配父级链中第一个带.card类的祖先:
console.log(document.querySelector("#myselector").closest(".card:not(:scope)"));
两种方法都能满足需求:第一种兼容性更好(适配旧版浏览器),第二种写法更简洁直观,你可以根据自己的场景选择。
内容的提问来源于stack exchange,提问作者LIGHT
相关产品推荐
相关产品推荐

