我有一个 HTML 标记,看起来像
<ul>
...
<li>
<ul class="x">
...
<a href="#"...
如何从链接上的点击事件中获取父 ul.x
元素?
this.parentNode
如果 UL 是父元素,则有效,但如果它是祖先元素之一,我必须使用 this.parentNode.parentNode
取决于有多少父元素元素介于两者之间...
我能以某种方式获得第一个 UL parent 吗?
最佳答案
由于您已将问题标记为 jQuery:
$(this).closest("ul"); //Get the first ancestor `ul`
$(this).closest("ul.x"); //Get the first ancestor `ul` with class `x`
或者,不使用 jQuery(因为您的示例似乎没有使用 jQuery):
var node = this;
while(node.tagName !== "UL") {
node = node.parentNode;
}
关于javascript - 获取 parent /祖先 UL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10431622/