Home > Back-end >  Partly editing inline style attribute of an element
Partly editing inline style attribute of an element

Time:01-21

It's currently working like such:

var ball = document.getElementById('ball');
//some code
let bml = parseInt(ball.style.marginLeft,10);
//if *conditional statement* is true, do:
ball.setAttribute("style","margin-left:" (bml-4) "px;");

But I'm trying to achieve it by writing this:

ball.style['marginLeft']=bml-4;

except the result isn't the same.

I've seen online examples of using this method to edit attribute values dynamically but they always seemed to use pre-calculated values like "400px" and never variables like my example, why is that?

CodePudding user response:

Style properties must be set with string values, as it is documented in the following link: https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/style#setting_styles

So it is possible to dynamically set style values by using String Literals:

ball.style['marginLeft']=`${bml-4}px`;
  • Related