代码之家  ›  专栏  ›  技术社区  ›  rahim asgari

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

  •  45
  • rahim asgari  · 技术社区  · 15 年前

    我要获取具有指定标记名的元素的父元素。

    示例代码:

    <table>
       <tr>
          <td>
              <input type='button' id='myId' />
          </td>
       </tr>
    </table>
    

    现在我想要这样的东西:

    $('#myId').specificParent('table'); //returns NEAREST parent of myId Element which table is it's tagname.
    
    3 回复  |  直到 15 年前
        1
  •  103
  •   jensgram    15 年前

    见 .closest() :

    获取与选择器匹配的第一个祖先元素,从当前元素开始并通过DOM树向上进行。

    即。,

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

    ( Demo )

        2
  •  8
  •   NimChimpsky    15 年前
    $('#myId').closest("table");
    
        3
  •  1
  •   Ulug'bek    12 年前

    $('#myId').parents('table') 也行