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 )
2 Answers 2
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.
-
\$\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\$Heretic Monkey– Heretic Monkey2014年10月24日 21:40:10 +00:00Commented Oct 24, 2014 at 21:40
-
\$\begingroup\$ @MikeMcCaughan Agreed. I do feel the 2nd one is easier to maintain. \$\endgroup\$konijn– konijn2014年10月25日 02:42:16 +00:00Commented Oct 25, 2014 at 2:42
<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.