2

I am trying to change a the width value of my div using javascript. Using:

document.getElementById("id").style.width = "25%";

works fine for string literals, but I want to set the value using a variable.

2
  • I believe this is the same question as this. Maybe I was wrong with understanding of your question, what have you tried and didn't work? Commented Nov 13, 2012 at 18:01
  • Hey, thanks for replying! Your solution would have worked great, but I needed to calculate a value and then append a string like "%" or "px". I don't quite know this ins and outs of javascript, and didn't know that you could convert from int to string just by appending a string. Commented Nov 13, 2012 at 18:38

1 Answer 1

5

When concatenating strings and variables javascript will use their string representation, try the following:

var variable = 25;
document.getElementById("id").style.width = variable + "%";
Sign up to request clarification or add additional context in comments.

4 Comments

just to be sure you can use variable.toString().
@OnurTOPAL. Just be sure to delete the comment, when you concat a variable with a string there is an implicit conversion to string. :)
@OnurTOPAL This behaviour is well defined. There is no need to explicitly call toString() - it would just be wasted keystrokes.
yes in this case it is not need but if you can check this url jsfiddle.net/S37vw I know y++ just convert it to int but that also means JS easily convert types. that s why I said to be sure.

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.