获取父DIV的ID

时间:2013-05-28 17:07:21

标签: jquery

我想获取特定ID的父DIV的ID。

这是HTML: -

<div id="sample-name" class="wrapper-dropdown-5" tabindex="2">
     <div class="m2">Heading</div>
         <ul class="dropdown">
             <div class="menu-border">
                   <li class="orange">
                       <a href="#2" data-jumpslide="2" data-goto="diagnostics">
                       ...
                  ...

<a>是点击的链接,单击它时,我需要父DIV的ID(样本名称)。

这就是我在<a>的点击功能中所做的: -

$(this).parents('div:eq(0)').attr('id').split(' ');

但是它给了我以下错误: -

  

未捕获的TypeError:无法调用未定义的方法'split'

你认为还有其他方式或者我可以改善吗?

感谢。

4 个答案:

答案 0 :(得分:4)

简单地说:

$(this).parents("div").filter(function(i) { return $(this).prop("id"); }).first().prop("id")
  • .parents()
    • 调用所选元素的所有父母
  • .filter()
    • 将一组匹配的元素减少为在
    • 中传递方法的元素
  • .first()
    • 选择一组匹配元素中的第一个
  • .prop()
    • 获取元素的“属性”

答案 1 :(得分:1)

为什么不在您要查找的父div上使用类(您的示例中为wrapper-dropdown-5)?像这样:

var parentId =  $(this).parents('div.wrapper-dropdown-5').prop('id') ;

答案 2 :(得分:1)

我的建议是使用closest

$(this).closest('[id]').attr('id');

返回id为

的最近父级的id

Quicky demo

编辑:在进一步审核之后,我得出的结论是,最好使用.parents('[id]')代替closestclosest包含活动元素,您不太可能希望包含它。

答案 3 :(得分:1)

另一种方法:

$(this).parents("div.m2").attr("id");

$(this).parents("ul").parent("div").attr("id");
相关问题