Question :
Hello,
I would like to know if you can select a class / element from a partially informed value, for example:
<div class="chart-piso c100 p100 orange big">
<span id="percPiso">100%</span>
<div class="slice">
<div class="bar"></div>
<div class="fill"></div>
</div>
</div>
I would like to select the elements only by stating that the classes contain p
before the numbers because those numbers are variable.
I tried to select them as follows and I know it’s super wrong too haha:
$("div[class*='chart-']").removeClass(div[class*='p']);
Any suggestions?
Thank you!
Answer :
If you understand what you are trying to do, you can use regex to remove the class that begins with p and has numbers later,
$("div[class^='chart-']").removeClass(function(index, className) {
return (className.match(/(p[0-9]+)/g) || []).join(' ');
});
console.log($("div[class^='chart-']").attr("class"));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><divclass="chart-piso c100 p150 orange big">
<span id="percPiso">100%</span>
<div class="slice">
<div class="bar"></div>
<div class="fill"></div>
</div>
</div>
The answer from @Lucas Costa already solves your problem in a great way, I’ll just post another possible way using String.replace()
.
var $divChart = $("div[class^='chart-']");
var divClasses = $divChart.prop('class');
$divChart.prop('class', divClasses.replace(/p[0-9]{3}/g, ''));
console.log('Classes da div: ' + $divChart.prop('class'));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><divclass="chart-piso c100 p100 orange big">
<span id="percPiso">100%</span>
<div class="slice">
<div class="bar"></div>
<div class="fill"></div>
</div>
</div>
An alternative to the response of @ pedro-camara-junior with pure JS, certain that was requested with jQuery, but sometimes not necessary, would be the use of querySelector()
:
var el = document.querySelector('div[class^=chart-]');
el.className = el.className.replace(/b(^|s)pd+b/g, '');
console.log("res: " + el.className);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><divclass="chart-piso c100 p100 orange big">
<span id="percPiso">100%</span>
<div class="slice">
<div class="bar"></div>
<div class="fill"></div>
</div>
</div>