cssText – Add Multiple Styles Using JavaScript

Home » cssText – Add Multiple Styles Using JavaScript

cssText – Add Multiple Styles Using JavaScript

cssText – Adding multiple styles to an element with vanilla JavaScript can feel a bit clunky. The most common approach I’ve seen to style elements with plain JavaScript is to grab your target element, and then add one style at a time.


// Select the element that you want to add style to it (via class here)
const el= document.querySelector(".js-style");

// Add style properties, one at a time (it's boring) = "#f00" = "#00f" "20px 10px" = "uppercase"

It works, but it’s boring, there’s too much repetition, and you are not applying the DRY concept (Don’t repeat yourself).

instead, you can use the cssText property.

Example: =
  "background-color: #f00; color: #00f; margin: 20px 10px; text-transform: uppercase";

This will work properly, but look at the code again, it can be more readable right?

let’s use the template literals. to get a syntax like CSS.

Example: = `
background-color: #f00;
color: #00f;
margin: 20px 10px;
text-transform: uppercase;

now the code is easier and more readable.

you can find more useful articles on AMK


I’m Front End Developer with more than 2 years of experience, I love to learn every day, and share this knowledge with other developers. if you are reading this now, I wish you have a great day!

No Comments on cssText – Add Multiple Styles Using JavaScript

Related Posts:


Best CSS Frameworks in 2021

1. Bootstrap 2. Foundation 3. Bulma 4. Tailwind CSS 5. UI Kit 6. Milligram 7. Materialize CSS Bootstrap Quickly design and customize responsive mobile-first sites


Music Player With Vanilla JavaScript

In this blog tutorial, we are going to set up and build a music player with vanilla JavaScript from scratch ‘without audio tag’, you can


Append and AppendChild in JavaScript

The append and appendchild Methods are too popular and used to add elements into the Document Object Model(DOM). But there is a main difference between


JavaScript Difference between Methods and Functions

JavaScript Functions: A function is a block of code written to perform some specific set of tasks. We can define a function using the function keyword, followed by Name and