0

I'm learning about changing css using javascript:

img.style.border-radius = "100%"
img.style.border = "9px solid #ffffff"
img.style.box-shadow = "0px 0px 5px #00000070"
img.style.margin = "20px"

how do I change styles with "-" in their names? It is probably simple but I did not find how.

Let me take this opportunity to ask: Is there a useful/efficiently way to do that using JS?

  • 1
    use camel case `borderRadius` ,`boxShadow` – Pranav C Balan Mar 28 '20 at 17:21
  • 1
    Does this answer your question? [Dynamically access object property using variable](https://stackoverflow.com/questions/4244896/dynamically-access-object-property-using-variable) – xdeepakv Mar 28 '20 at 17:32

2 Answers2

2

You can use this notation (square bracket notation):

const x = document.querySelector("div");
x.style["border-radius"] = "100%";
x.style.border = "9px solid #ffffff";
x.style["box-shadow"] = "0px 0px 5px #00000070";
x.style.margin = "20px";
x.style["text-align"] = "center";
<div>Hi there</div>
KooiInc
  • 119,216
  • 31
  • 141
  • 177
0

Sympol "-" is JavaScript arithmetic operator of subtraction. You should use camel case style to mark up different words of CSS properties, change css-styled border-radius into js borderRadius. Correct is:

img.style.borderRadius = "100%"
img.style.boxShadow = "0px 0px 5px #00000070"
focus.style
  • 6,612
  • 4
  • 26
  • 38
  • 1
    Hey focus.style ! Code-only answers may solve the problem but they are much more useful if you explain how they solve it. Community requires theory as well as code both to understand your answer fully. – RBT Mar 30 '20 at 00:56
  • Thanks for the advice. Changed the answer. – focus.style Mar 30 '20 at 12:40