JavaScript — Changing CSS Styles

Gerald Clark
2 min readJun 25, 2024

--

In the last article I covered changing the style of an html element by directly changing the style attribute using setAttribute. There is a drawback to this method though.

Here I have a h1 being colored orange.

Lets say we want to add another style attribute that gives the title a margin of 50 pixels. I can do this in JavaScript via the setAttribute method.

Now the orange color style attribute has been overwritten.

I want to be able to add more styles, not overwrite them!

I can do this via the style property. When I log the style property, you can see this huge object in the console with all these different properties and you can see that “color” has been set to orange.

So I can access the margin property and change it that way. Like so,

There are lots of ways to go about doing the same thing in JavaScript and many other programming languages. Using the style property is just a more versatile way of doing things.

--

--

Gerald Clark
Gerald Clark

Written by Gerald Clark

Father Game Developer Music Composer Sound Designer

No responses yet