基于子类选择元素 [英] Select element based on child class
问题描述
CSS中是否有一种方法来选择一个具有给定类的子元素的元素?
Is there a way in CSS to select an element which has a sub-element with given class?
我想将样式应用到<$ c $
I want to apply a style to a <ul>
list that has <li>
with a particular class.
推荐答案
这是css不可能的,因为你是通过选择一个基于后代的祖先来反对级联。
This isn't possible with css, since you're working against the cascade by selecting an ancestor based on a descendant.
我可以提供的最好的建议是一个jQuery方法:
The best I can offer and suggest is a jQuery approach:
$(document).ready(
function() {
$('.givenClassName').parent().addClass('something');
}
);
这会找到 givenClassName
然后选择其父元素,并将 something
添加到该元素。
This finds the element with the givenClassName
and then selects its parent element and adds the class something
to that element.
@Blaenk 提出了一种替代方法,它更灵活(他的方法不需要祖先元素作为父元素你选择的元素)。
@Blaenk suggests an alternate approach, which is more versatile (his approach doesn't require the ancestor element to be the parent of the element you're selecting by).
显然,其他JS库和JS本身,可以实现相同的效果,虽然我不能提供特别的建议,因为我还只是熟悉JS和大部分的jQuery(为什么是,我羞于自己...)。
Obviously other JS libraries, and JS all by itself, can achieve the same effect, though I can't offer particular advice, since I'm still only just familiarising myself with JS and mostly with jQuery (why yes, I am ashamed of myself...).
这篇关于基于子类选择元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!