Henrik Baecklund
Henrik Baecklund

Reputation: 43

Subtract number in span

I would like 5 left do -1 e.g. become 4 left.

HTML

<span class="small">5 left</span>

jQuery

// Store the 5 left in "numberStock" variable
var numberStock = parseInt($(".small:first").text());

// Subtract with "numberStock -1"
var minusStock = numberStock - 1;

// Here comes the issue, how do I add the new content?
$(".small:first").attr(minusStock "left");

Question

How do I add the new numberStock number 4 and text left?

Upvotes: 1

Views: 524

Answers (4)

Pranav C Balan
Pranav C Balan

Reputation: 115242

Use String#replace method with a callback function.

// use text method with callback where second 
// argumnet is old text
$(".small:first").text(function(i, txt) {
  // replace text with decremented value
  return txt.replace(/\d+/, function(m) {
    return m - 1;
  });
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="small">5 left</span>


UPDATE : With pure JavaSript do something like this.

// since you just want the first element use
// querySelector otherwise you need to use 
// querySelectorAll and then need to iterate 
// over them
var ele = document.querySelector(".small");

// update text content of span element
ele.textContent = ele.textContent.replace(/\d+/, function(m) {
  return m - 1;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="small">5 left</span>

Upvotes: 1

Ionut Necula
Ionut Necula

Reputation: 11480

You can use replace:

// Store the 5 left in "numberStock" variable
var numberStock = parseInt($(".small:first").text());

// Subtract with "numberStock -1"
var minusStock = numberStock - 1;
console.log(minusStock);
// Here comes the issue, how do I add the new content?
var original = $(".small:first").text();
var toAdd = original.replace(original[0], minusStock);
$(".small:first").text(toAdd);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="small">5 left</span>

Upvotes: 1

rule
rule

Reputation: 281

i am not sure if i understood your question, but if i did here is a way to do it , which is pretty close to what you were trying to achieve

var numberStock = parseInt($('.small').text())
var minusStock = numberStock - 1;
$('.small').text(minusStock + ' left');

here is a fiddle in case you want to test around with it https://jsfiddle.net/09wcjp7b/

Upvotes: -1

Nina Scholz
Nina Scholz

Reputation: 386736

A solution in plain Javascript

Array.prototype.forEach.call(document.getElementsByClassName('small'), function (a) {
    a.innerHTML = a.innerHTML.replace(/\d+/, function (v) {
        return v - 1;
    });
});
<span class="small">5 left</span>

Upvotes: 1

Related Questions