JQuery 查找具有特定类前缀的第一个父元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7457618/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 23:52:57  来源:igfitidea点击:

JQuery find first parent element with specific class prefix

jqueryjquery-selectors

提问by Time Travel

I want to get the first parent which has a specific class prefix, suppose:

我想获得具有特定类前缀的第一个父级,假设:

<div class="div-a3332"> 
  <div class="div-a89892">
    <p>
      <div class="div-b2">
        <div id="divid">hi</div>
      </div>
    </p>
  </div>
</div>

For example, my current element is #dividand I want to find the first element that has the class prefix div-a. So basically it will select:

例如,我的当前元素是#divid并且我想找到第一个具有类前缀 div-a 的元素。所以基本上它会选择:

<div class="div-a89892">

回答by Matt Ball

Use .closest()with a selector:

使用.closest()与选择:

var $div = $('#divid').closest('div[class^="div-a"]');

回答by Sunny R Gupta

Jquery later allowed you to to find the parents with the .parents()method.

Jquery 后来允许您使用该.parents()方法查找父项。

Hence I recommend using:

因此我建议使用:

var $div = $('#divid').parents('div[class^="div-a"]');

This gives all parent nodes matching the selector. To get the first parent matching the selector use:

这给出了匹配选择器的所有父节点。要获取与选择器匹配的第一个父级,请使用:

var $div = $('#divid').parents('div[class^="div-a"]').eq(0);

For other such DOM traversal queries, check out the documentation on traversing the DOM.

对于其他此类 DOM 遍历查询,请查看有关遍历 DOM的文档。