user3344734 user3344734 - 4 days ago 7
jQuery Question

Compare number when there is a colon prefix

I need to set a class if the string in the element below has a value higher than 0.

The script works if I remove the strong part and the colon, but I canĀ“t control this so how do i targets this?

Script:

$('.stockinfo.col4').filter(function(index){
return parseInt(this.innerHTML) > 0;
}).addClass("instocktest");


HTML:

<div class="stockinfo col4"><strong>Stock</strong>: 0<span></span></div>
<div class="stockinfo col4"><strong>Stock</strong>: 50<span></span></div>

Answer

Use .textContent to get the text without any HTML tags. And remove everything except the digits before converting to a number

$('.stockinfo.col4').filter(function(index) {
  return parseInt(this.textContent.replace(/\D/g, '')) > 0;
}).addClass("instocktest");
.instocktest {
  background-color: green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="stockinfo col4"><strong>Stock</strong>: 0<span></span>
</div>
<div class="stockinfo col4"><strong>Stock</strong>: 50<span></span>
</div>

Comments