1

I have a variable as such:

var is_last = $('.paging a:last').attr('rel');

this returns '-400' which is correct.

However, i need to add 200 to this so the answer is '-200'

if i do this:

var is_last = $('.paging a:last').attr('rel')+200;

the variable is now '-400200'

How can i pass the variable as a value?

A.

2 Answers 2

7

You need to parse the output of .attr(), it to an integer first using parseInt() so you're dealing with a number (and not a string), like this:

var is_last = parseInt($('.paging a:last').attr('rel'), 10) + 200;
Sign up to request clarification or add additional context in comments.

Comments

0

I reckon that @Nick Craver is correct and that parseInt is the more correct answer, but as a quick-and-dirty alternative you can also convince javascript that a variable is a number and not a string by multiplying by 1:

    var x = parseInt("-400", 10) + 200;
    var y = ("-400" * 1) + 200;

    alert(x);
    alert(y);

2 Comments

You can do this, but it's much slower, you can test it here, +"-400" would be the operator shortcut with decent performance here :)
Very good comparison tool, the marked improvement in js performance on Chrome 8 compared to Chrome 7 suggests that I should upgrade immediately. Also it is odd how the 6 different techniques would result in markedly different performance in different browsers or versions of browsers - on my Chrome 7 setup, parseInt is the slowest on those benchmarks. Thanks again I will use this reference in conversations!

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.