在jQuery中识别继承的CSS类

时间:2018-07-13 06:34:25

标签: jquery

我有以下代码:

<style>
.foo{
color:red;
}
</style>

<div class="foo">
<span>Hello</span>
</div>

我有下面的jquery代码来检查span标签是否具有foo类。

$("span").hasClass("foo")

这将返回false。但我希望它返回true。如何在jquery中检查继承的CSS类?

3 个答案:

答案 0 :(得分:1)

我会选择一个带有选择器的.closest()

$('span').closest('.foo').length > 0

console.info('span has foo?', 
  $('span').closest('.foo').length > 0)

console.info('span has bar?', 
  $('span').closest('.bar').length > 0)
  
console.info('span has baz?', 
  $('span').closest('.baz').length > 0)
  
console.info('span has whatever?', 
  $('span').closest('.whatever').length > 0)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<main class="baz">
  <div class="foo">
    <span class="bar">Hello</span>
  </div>
</main>

答案 1 :(得分:1)

使用.closest('.foo').closest()在父元素和当前元素(因此,跨度是父元素)上搜索选择器

$('span').each(function() {
  console.log($(this).closest('.foo').length > 0)
})
.foo {
  color: red;
}

.bar {
  color: blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="foo">
  <span>Hello</span>
</div>
<div>
  <span class="foo">Hello</span>
</div>
<div>
  <span class="bar">Hello</span>
</div>

答案 2 :(得分:0)

使用$("span").closest('div')

if($("span").closest('div').hasClass("foo")){
  console.log('found');
}
.foo{
  color:red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="foo">
<span>Hello</span>
</div>