2

How is it possible to count a variable inside of a innerHTML?

JS

var counter = 1;
counter++;
alert(counter);

$(".end").html('Test ' + counter+1 + ' Test');

HTML

<p class="end"></p>

In my JSfiddle example, it works for alert example, but not in the innerHTML element. Why? How is it getting work?

6 Answers 6

3

Its because you are doing string concatenation.

Current evaluation

'Test ' + counter+1 + ' Test'
'Test 2' +1 + ' Test'
'Test 21' + ' Test'
'Test 21 Test'

You should wrap your calcualtion insde ()

$(".end").html('Test ' + (counter+1) + ' Test');

When you add () that takes higher precedence and calculates first in the expression.

Current evaluation

'Test ' + (counter+1) + ' Test'
'Test ' + 3 + ' Test'
'Test 3' + ' Test'
'Test 3 Test'
Sign up to request clarification or add additional context in comments.

Comments

0

Is not adding.Just act like string.Add some () .Then it was added .try this $(".end").html('Test ' +(counter + 1) + ' Test');

var counter = 1;
counter++;
alert(counter);

$(".end").html('Test ' +(counter + 1) + ' Test');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p class="end"></p>

Comments

0

This happens because initially Test + counter this converts counter int 2 to string hence addition happens as string try wrapping those in brackets as (counter + 1)

$(".end").html('Test ' + (counter+1) + ' Test');

Check fiddle

For more info regarding the + operator see this specification

Comments

0

Just use Brackets, and it will work :

var counter = 1;
counter++;
alert(counter);

$(".end").html('Test ' + (counter+1) + ' Test');

Comments

0

You have to add brackets to your code JS Fiddle. Like this

$(".end").html('Test ' +( counter + 1 )+ ' Test');

Comments

0

Use parseInt for math calculation other wise its only string concatenation.

var counter = 1;
counter++;
alert(counter);

$(".end").html('Test ' + parseInt(counter+1) + ' Test');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p class="end"></p>

2 Comments

Its better to use for calculation.
Better in which aspect ?

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.