1

This is a basic question, but I somehow can't find the answer.

I would like to pass a mix of string and variable as the value for an attribute, in the setAttribute() method.

This is what I have:

    document.getElementById('mydiv').setAttribute("style", "width: 10%")

Instead of "width: 10%" I would like to have something like: "width: --myVar-- %"

All questions I find are related to passing only a variable but not how to mix both variable and string.

Thanx for any help!

2
  • You need to concatenate your string with your variable. Commented Nov 10, 2020 at 10:52
  • Try this: var foo = 20; document.getElementById('mydiv').setAttribute('style', 'width: '+ foo +'px'); Commented Nov 10, 2020 at 10:56

2 Answers 2

1

You can use this way.

document.getElementById('mydiv').setAttribute("style", "width:"+ myVar+ "%")
Sign up to request clarification or add additional context in comments.

Comments

1

You shouldn't even be using setAttribute when there's a direct property and accessors:

document.getElementById('mydiv').style.width = myVar + '%';

Comments

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.