JavaScript

How to use JavaScript to change CSS properties

February 23, 2022

How to use JavaScript to change CSS properties

In this article we will learn how to use JavaScript to change CSS properties, in an easy to learn and fast way, for you to style elements with JS.

How to use JavaScript to change CSS cover

What’s up programmer, ok? Let’s learn how to add CSS with JS!

The idea behind this technique is very simple, first we need to select the target element

Whether by class, id or query selector, for this you can use the methods:

  • getElementById
  • getElementsByClassName
  • querySelector or querySelectorAll

Once this is done, you need to access the style property of the selected element, and make changes to the CSS

Remembering that rules like background-color that have two words, you should replace it with camelCase like this: backgroundColor

Let’s take a practical example:

<p id="paragraph">This paragraph will have its CSS changed!</p>

And this is what appears in the browser:

Well, here we have a p tag, with a paragraph id, now let’s select this element and change its style with JavaScript

let el = document.getElementById('paragraph');

el.style.color = 'red';

el.style.cssText =
 'color: blue;' +
 'background-color: yellow;' +
 'border: 1px solid magenta';

Here we have two ways to change CSS, a single property and a multi-property one.

The first option is to put each property on a line, which can be quite expensive if we want to style the component a lot

In the second form, we concatenate a string over several lines, which gives an impression of CSS and is organized, to reach several properties at once

It’s up to your choice and need

And of course, when a line of code changes a property that already had a value before, the previous one is replaced (which is the case with color )

Here’s how it looks in the browser:

The element received all the styles from the second rule, and the one from the first was replaced

And this is how we change CSS with JavaScript 😀

Conclusion

In this article we learned how to use  JavaScript to change CSS properties

We need to select the element and then change the style property with the rule we want to change in CSS, for example border

Then we enter the values and the CSS is changed

There is the possibility to change multiple rules with the cssText property, but we need to pass a string with all of them

Want to learn more about JavaScript? Click here!

Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x