[英]How to get the first parent that has a certain CSS property using jQuery?
I need to get the first parent that has position:relative
. 我需要得到第一个有
position:relative
父母position:relative
。 Something like in the example below but my real content will be dynamically generated. 类似于下面的示例,但我的真实内容将动态生成。
<div id="parent1" style="position:relative">
<div id="parent2">
<div id="my-element" style="position:absolute"></div>
</div>
</div>
Do you know a simple way to do this using jQuery? 您是否知道使用jQuery执行此操作的简单方法?
You can filter
the set of parents()
, and grab the first element matching your filter: 您可以
filter
一组parents()
,并获取与您的过滤器匹配的第一个元素:
$('#my-element')
.parents()
.filter(function() {
return $(this).css('position') == 'relative';
}).first();
Demo ( Works with classes, too ) 演示 (也适用于课程 )
I would recommend you to add a class instead of changing directly the style and then looking for that class using jQuery. 我建议你添加一个类,而不是直接更改样式,然后使用jQuery查找该类。 Is much more simple and intuitive.
更加简单直观。
CSS: CSS:
.active{
position:relative;
}
HTML: HTML:
<div id="parent1" class="active">
<div id="parent2">
<div id="my-element"></div>
</div>
</div>
jQuery: jQuery的:
//getting the first element with .active class
$('#my-element').closest('.active')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.