jQuery 如何使用jquery通过指定的标签名称获取父元素?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4185610/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get parent element by specified tag name using jquery?
提问by rahim asgari
I want to get an Element's parent which has an specified tag name.
我想获得一个具有指定标签名称的 Element 的父级。
Sample code:
示例代码:
<table>
<tr>
<td>
<input type='button' id='myId' />
</td>
</tr>
</table>
Now i want something like this:
现在我想要这样的东西:
$('#myId').specificParent('table'); //returns NEAREST parent of myId Element which table is it's tagname.
回答by jensgram
See .closest()
:
Get the first ancestor element that matches the selector, beginning at the current element and progressing up through the DOM tree.
获取与选择器匹配的第一个祖先元素,从当前元素开始并向上遍历 DOM 树。
I.e.,
IE,
$('#myId').closest('table')
(Demo)
(演示)
回答by NimChimpsky
$('#myId').closest("table");
回答by donah
$('#myId').parents('table')
works as well
$('#myId').parents('table')
也能用