1
\$\begingroup\$

So let's take this code which increments a Javascript text field value:

<div id="counter">1</div>
var counter = $(".counter")
counter.html( parseInt(counter.html()) + 1 )

It can be made shorter by using the Unary operator + which behaves like Number():

<div id="counter">1</div>
var counter = $(".counter")
counter.html( +counter.html() + 1 )

is there a shorter and better way to do this?

I tried combinations of the ones below, neither work:

<div id="counter">1</div>
$(".counter").html( +this.innerHTML + 1 )

and

<div id="counter">1</div>
$(".counter").html( +this.value + 1 )

and

<div id="counter">1</div>
$(".counter").html( +$this.html() + 1 )
\$\endgroup\$
0

2 Answers 2

7
\$\begingroup\$

Not a question that fits CR well. This is clearly short, untested sample code. You need $("#counter"), not $(".counter").

var counter = $("#counter")
counter.html( parseInt(counter.html()) + 1 )
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="counter">1</div>

If you truly wish to increase the content of a field that you access by id you could try this:

document.getElementById('counter').textContent++;
<div id="counter">1</div>

This works as of IE9.. Personally I would always make sure that there is a number in textContent since otherwise the value will become NaN which looks like amateur hour.

\$\endgroup\$
2
  • \$\begingroup\$ I ran a few variations through jsPerf, and found the second one here is by far the fastest (in Chrome 38 on Win8.1). Note that the first one still was able to perform that operation 36,446 times in a second. So unless you're incrementing something every 36 microseconds, or 0.36 ms, I wouldn't worry about which one is faster. I'd worry about which one is the easiest to maintain. \$\endgroup\$ Oct 24, 2014 at 21:40
  • \$\begingroup\$ @MikeMcCaughan Agreed. I do feel the 2nd one is easier to maintain. \$\endgroup\$
    – konijn
    Oct 25, 2014 at 2:42
5
\$\begingroup\$
<div id="counter">1</div>
var z = $(".counter")
z.html( +z.html()+1)

21 characters saved.

Stupid joke aside, I think you shouldn't worry about this so much. There's probably other places in your code where you're spending far more resources. This is a textbook example of a micro-optimization. You're worrying about incrementing a value by 1 and in the meantime you ignore the more complex parts of your code.

\$\endgroup\$
0

Your Answer

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