I’m trying to subtract 1 (one) from a value with jQuery. I’ve managed to do so like this:
$('.notis').text(parseInt($(".notis").text()) - 1);
Problem is that the <a> this is subtracting from looks like this:
<a href="#" class="notis"><img src="/images/icons/picture.png">3</a>
So the jquery above will subtract 1 (one) from the value, but also remove the image! How can I do this and keep the image html?
You can store the image in a temporary variable, then add it to the node using the
prependmethod:Demo: http://jsfiddle.net/sPnhL/
Additional notes:
parseInt( ... , 10)instead ofparseInt( ... ). Numbers prefixed by a zero will be treated inconsistently across browsers. By specifygin the radix of 10, the number will be parsed correctly.$('.notis')selects all elements with classnotis. When you’re using$('notis').text($('notis').text()-1), all elements with classnotiswill contain the value of the first.notiselement (because$('.notis').text()returns the value of the first.notis). That’s why I used.eachin my code.$(this)more than once, it’s worth storing the variable$(this)in a temporary variable, for improved efficiency.