# Increment a text field value

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 )


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. • 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. – Heretic Monkey Oct 24 '14 at 21:40 • @MikeMcCaughan Agreed. I do feel the 2nd one is easier to maintain. – konijn Oct 25 '14 at 2:42 <div id="counter">1</div> var z =$(".counter")