Question

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?

Was it helpful?

Solution

You can store the image in a temporary variable, then add it to the node using the prepend method:

$('.notis').each(function() {
    var $this = $(this);                        // <-- Reference to current elem
    var $img = $this.find('img');               // <-- Reference to <img>
    $this.text(parseInt($this.text(), 10) - 1); // <-- Your logic
    $this.prepend($img);                        // <-- Add image again.
});

Demo: http://jsfiddle.net/sPnhL/

Additional notes:

  • Use parseInt( ... , 10) instead of parseInt( ... ). 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 class notis. When you're using $('notis').text($('notis').text()-1), all elements with class notis will contain the value of the first .notis element (because $('.notis').text() returns the value of the first .notis). That's why I used .each in my code.
  • When you're going to use $(this) more than once, it's worth storing the variable $(this) in a temporary variable, for improved efficiency.

OTHER TIPS

There might very well be a better solution but you can save the children of the link element and re-attach them after you change the text:

$('.notis').each(function (index, element) {
    var $children = $(this).children();
    $(this).text(parseInt($(this).text()) - 1).prepend($children);
});

Here is a demo: http://jsfiddle.net/epuxy/ (see the number on the bottom change when you click on the link)

I'd suggest to wrap up the number in a <span> and replace its content.

Wrap the 3 in a div or span (preferred) class and do it from there.

The best solution is to put a span around your number. This results in the best performance.

Html

<a href="#" class="notis"><img src="/images/icons/picture.png"><span>3</span></a>

jQuery

$('.notis > span').text(parseInt($(".notis").text()) - 1);

Check out this jsFiddle

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top