如何使用jquery通过指定的标记名称获取父元素?

时间:2021-09-23 19:00:10

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.

3 个解决方案

#1


98  

See .closest():

请参阅.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.,

即,

$('#myId').closest('table')

(Demo)

(演示)

#2


8  

$('#myId').closest("table");

#3


1  

$('#myId').parents('table') works as well

$('#myId')。parents('table')也适用

#1


98  

See .closest():

请参阅.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.,

即,

$('#myId').closest('table')

(Demo)

(演示)

#2


8  

$('#myId').closest("table");

#3


1  

$('#myId').parents('table') works as well

$('#myId')。parents('table')也适用