如何检查CSS类中是否存在子字符串并将其删除?

时间:2018-08-06 18:35:23

标签: jquery html css

我们有几个CSS类,其模式如下。它们都以bg--color--开头。如何使用jQuery检查元素是否包含CSS类子字符串,如果找到,则将其删除?

示例:

  1. bg--white
  2. bg--red
  3. bg--orange
  4. color--orange
  5. color--red
  6. color--purple

我尝试过的

$(function() {
  var divEl = $('div');
  if(divEl.hasClass('*=bkg--') {
    divEl.removeClass('*=bkg--'); 
  }
  if(divEl.hasClass('*=color--') {
    divEl.removeClass('*=color--'); 
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="bkg--red color--white">Holisticly build resource sucking methodologies before distributed methodologies. </div>
<div class="bkg--orange color--white">Phosfluorescently integrate revolutionary collaboration and idea-sharing through efficient services.</div>
<div class="bkg--purple color--purple">Credibly maximize impactful e-tailers with resource-leveling convergence. </div>

1 个答案:

答案 0 :(得分:1)

您可以访问所需的.prop() (在您的情况下为"class",并使用JS的String.prototype.replace()

快速更改它

$("div").prop("class", function( i, cls ) {

  console.log("Before: "+ cls )
  cls = cls.replace(/(^|\s)(bg|color)--\S+/g, '');
  console.log("After: "+ cls )
  
  return cls;
});
.bg--white {background: white;}
.bg--red {background: red;}
.bg--orange {background: orange;}
.color--orange {color: orange;}
.color--red {color: red;}
.color--purple {color: purple;}
<div class="test bg--red color--white">Holisticly</div>
<div class="foo--bar bg--orange color--white">Phosfluorescently</div>
<div class="bg--purple color--purple">Credibly</div>

<script src="//code.jquery.com/jquery-3.1.0.js"></script>

或者简单地:

$("div").prop("class", function( i, cls ) {
  return cls.replace(/(^|\s)(bg|color)--\S+/g, '');
});

或者如果您使用JS编译器(例如Babel.js)

$("div").prop("class", (i, c) => c.replace(/(^|\s)(bg|color)--\S+/g, ''));

此外,您可以将选择器更改为:

,而不是使用过于通用 $("div")
$("[class^='bg--'], [class*=' bg--'], [class^='color--'], [class*=' color--']")

虽然有点长,但是可以很好地完成工作。