1

I want to add a number to a particular jQuery Object like this.

$('#count').text(Number($('#count').text()) + 1);

It works, but it's a little redundant to write same selector and text() method twice. Is there better way to do this with jQuery, like $('#count').text(Number(this) + 1);?

6
  • how about $('#count').text(Number($(this)) + 1); Commented Feb 10, 2014 at 12:01
  • there is - don't use the document as your primary data storage. Commented Feb 10, 2014 at 12:02
  • @C-link This doesn't work neither. Commented Feb 10, 2014 at 12:05
  • 1
    @C-link In this context this will be a Window. Commented Feb 10, 2014 at 12:06
  • @c-link that probably won't work. And if it does, you can replace both occurences of the selection Commented Feb 10, 2014 at 12:06

1 Answer 1

5

Yes, with the callback argument to $.fn.text:

$('#count').text(function(i, oldText) {
    return +oldText + 1;
});

Within the callback, oldText is set to the existing value. We use the unary plus + operator to convert it to a number (this is better than using Number()). The return value of the callback is set as the element's new text value.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.