jquery 如果只有某个子元素存在,如何将CSS应用于父元素?

omtl5h9j  于 9个月前  发布在  jQuery
关注(0)|答案(2)|浏览(113)

此问题在此处已有答案

Is there a CSS parent selector?(33个答案)
上个月关门了。
是否有一种方法可以使用CSS来应用样式到父元素,只有当父元素有一个特定的子元素?
下面是我的HTML:

<div class="Environment">
    <div class="col-md-6 interior_environment">
        <div class="aboutEnvironment">
            <div class="col-sm-12 col-md-12">
                <div class="title_environment"></div>
                <div class="description_environment">
                    <p><span>The natural environment or natural world encompasses all living and non-living things occurring naturally, meaning in this case not artificial. The term is most often applied to Earth or some parts of Earth.</span></p>
                </div>
            </div>
        </div>       
    </div>
</div>

字符串
我想添加下面的CSS(下面提到)到.Environment.interior_environment只有当.aboutEnvironment类存在于. Environment .interior_environment
如果. Environment .interior_environment中没有.aboutEnvironment类,则不应将此CSS添加到.Environment.interior_environment中。

.Environment
{
  display: block;
}
.interior_environment
{
  flex: 1;
}


有没有一种方法可以使用CSS来实现这一点,或者必须通过JavaScript来实现?

44u64gxh

44u64gxh1#

是的,还有其他几种方法,请尝试下面一个:
1.这将搜索类模式并应用所需的样式:

div[class*="aboutEnvironment"]{
 /* Write css style that  you want to apply  */
}

字符串
1.这将应用并检查类是否存在,但它可能不支持在火狐只是检查一次休息其他浏览器已添加支持这一个,refer
div:has(> aboutEnvironment){ > /* 写入要应用的样式 / }
1.你也可以使用get元素by className,然后将你的类应用到它。使用:
第一个月
1.请尝试:
.Environment > .interior_environment > .aboutEnvironment { /
写入要应用的样式 */ }
5.你也可以试试this

5w9g7ksd

5w9g7ksd2#

您可以使用以下jQuery来实现这一点:

$(document).ready(function() {
    if ($('.Environment .interior_environment .aboutEnvironment').length > 0) {
        $('.Environment').css('display', 'block');
        $('.interior_environment').css('flex', '1');
    }
});

字符串
这是一种简单的方法,你也可以尝试更复杂的方法来检查每个子节点或父节点,但那不是那么简单。
通过使用上面的方法,如果.aboutEnvironment不存在于其他两个类中,则该条件将返回false。
请记住,这只适用于页面中只有一个这样的元素,如果有多个这样的元素,则需要使用jQuery的子元素和父元素功能。

相关问题