0

I am trying to get a value from Javascript into my HTML code for a value in padding. I have a javascript function that defines the variable i.

function myFunction() {
  var i = 90;
}

I want to use that variable for padding in a div element like this.

The variable i from Javascript
              ↓
<div padding=" ">text</div>

But I don't know how to get that from Javascript into HTML (I'm sort of new to it and coding).

I have tried looking up on how to get Javascript values into HTML, but nothing has helped. Can you help?

3
  • so select the element with javascript and set the style property for padding. Commented Nov 12, 2019 at 0:12
  • In other words, go the other way, from JavaScript, set the property on the element, rather than trying to go from HTML to JavaScript. Also, note that HTML elements don't have padding attributes like that that control their visible padding styles. You have to set their style attributes using something called the CSSOM. See for example changing top padding in javascript Commented Nov 12, 2019 at 0:16
  • is padding related to style or just an attribute? Commented Nov 12, 2019 at 0:23

1 Answer 1

2

This should do:

function myFunction() {
  var i = "90px";
  document.getElementById("div1").style.padding = i;
}

myFunction();
#div1 {
  background-color:green;
}
<div id="div1">Padding is added around me by javascript.</div>

Sign up to request clarification or add additional context in comments.

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.