softcode softcode - 1 year ago 48
jQuery Question

Number parsing working in console but not in script

Here's my simple function, which is being called on the element as


function incrementValue(plusElement) {
var choicesLeft = jQuery("#choicesLeft");

choicesLeft.innerHTML = Number(choicesLeft.innerHTML) - 1;

line prints out a NaN in the console.

However when I enter this line in the console:

choicesLeft.innerHTML = Number(choicesLeft.innerHTML) - 1;

The expected behavior occurs.

Any ideas ?

Answer Source

innerHTML will not work here since you call it on jQuery object.

Use text() instead of innerHTML :

choicesLeft.text( Number(choicesLeft.text()) - 1 );

Hope this helps.

function incrementValue() {
  var choicesLeft = jQuery("#choicesLeft");

  choicesLeft.text( Number(choicesLeft.text()) + 1 );
<script src=""></script>
<button onClick='incrementValue()'>Increment</button>
<span id='choicesLeft'>0</span>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download