简体   繁体   English

如何使用jQuery获取具有某个CSS属性的第一个父级?

[英]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.

相关问题 使用Jquery具有具有某些CSS属性的元素的目标元素 - Target element that has an element with certain a CSS property using Jquery jQuery-如果子元素具有某些CSS类,如何将CSS添加到父元素 - jQuery - How to add css to a parent element if child element has certain css class 如何使用JQuery获取CSS属性的值? - How to get the value of a CSS property using JQuery? 如何使用jquery将css属性添加到具有特定属性的元素? - How to add css property to element has specific attribute using jquery? 如何使用jQuery获取具有某些属性的标签数量? - How to get the number of tags having certain property using jquery? 仅在具有特定功能的情况下才使用jquery更改CSS属性值 - Change a CSS property value with jquery only when it has a certain function 如何通过jQuery在给定的属性中获取具有特定类的所有父元素,并且其子元素具有特定的字符串值? - How can I get all parent elements that has a certain class and their children has a certain string value in their given attributes via jQuery? 如何使用 JS/JQuery 获取有用的 css 属性数据? - How to get useful css property data using JS/JQuery? jQuery获取具有特定类的所有元素并删除CSS属性 - JQuery get all elements with a certain class and remove a CSS property 如何获取第一个jQuery对象的父对象? - How to get parent of first jQuery object?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM