How to Add Styles to Element in Vanilla JavaScript

How to Add Styles to Element in Vanilla JavaScript

Learn about various ways of adding styles to elements in JavaScript
Ferenc Almasi β€’ 2022 May 19 β€’ Read time 4 min read
  • twitter
  • facebook
JavaScript

To add styles to an element in vanilla JavaScript, you can use the following helper function which expects a DOM element and a list of styles as an object:

Copied to clipboard! Playground
const style = (node, styles) => Object.keys(styles).forEach(key => node.style[key] = styles[key])

// Use it in the following way:
const element = document.querySelector('h1')

style(element, {
    background: 'black',
    color: 'yellow'
})

This works by looping through the keys of the styles object which it expects as a second parameter. In this case: background and color. Then, for each key, it sets the appropriate style property of the passed DOM element. This means you have to name the keys as valid CSS properties. Essentially, in the loop, this will translate to the following:

Copied to clipboard!
element.style.background = 'black'
element.style.color = 'yellow'

Manually set the style object of the element

This takes us to the second example, where you could also directly do the above and set the styles of an element by using assignments:

Copied to clipboard!
const element = document.querySelector('h1')

element.style.background = 'black'
element.style.color = 'yellow'

To find out what CSS properties are available on the element you are working with, simply grab an element and log its style object to the console. This will give back a CSSStyleDeclaration object:

Copied to clipboard! Playground
<- element.style

// Gives back
-> CSSStyleDeclaration {
    accentColor: ""
    additiveSymbols: ""
    alignContent: ""
    ...
}

Notice that styles that otherwise use dashes in CSS are converted into camelCase in JavaScript. For example, instead of "align-content", you can reference alignContent.


Using the cssText property

There is also a cssText property on the style object. This contains all the styles represented as a single string. Keeping with the above example, our element's cssText would be the following:

Copied to clipboard! Playground
'background: black; color: yellow;'

// Or you can overwrite it in the following way:
const element = document.querySelector('h1')

element.style.cssText = 'background: black; color: yellow;'

Make sure you pass a string to this property. All CSS properties must be separated by a semi-colon. You can also combine this approach with a more declarative function that generates the necessary styles out of JavaScript objects:

Copied to clipboard! Playground
const book = {
  content: 'πŸ“’',
  display: 'block',
  padding: '20px',
  background: 'yellow'
};

const getStyles = obj => Object.keys(obj).map(key => `${key}:${obj[key]}`).join(';');

// Later you can call the function to inline the styles
getStyles(book);

// Or assign it directly to your cssText
element.style.cssText = getStyles(book)

This function works by (similarly to the previous helper function):

  • First looping through the keys of the object with Object.keys
  • For each key, it returns with a new string (the key and value combined), by calling map
  • Lastly, it joins everything together with a semicolon, using join

If you have multiple styles to take care of, you can also take this one step further and use the below assignment to generate them in one go:

Copied to clipboard! Playground
const styles = {
    heroCTA: {
        display: 'block'
    },
    heroImage: {
        display: 'block',
        width: '100%'
    }
};

const getStyles = obj => Object.keys(obj).map(key => `${key}:${obj[key]}`).join(';');

const generatedStyles = Object.fromEntries(
    Object.entries(styles)
          .map(([element, style]) => [element, getStyles(style)])
);

// This will generate the following object:
{
    heroCTA: 'display:block',
    heroImage: 'display:block;width:100%'
}
Looking to improve your skills? Check out our interactive course to master JavaScript from start to finish.
Master JavaScriptinfo Remove ads

Using a style tag

Lastly, you can also dynamically create a style tag and append it to the body to add global styles to your app via JavaScript. To do this, you can use the following code snippet:

Copied to clipboard! Playground
const style = document.createElement('style')

style.innerHTML = `
    h1 {
        background: 'black';
        color: 'yellow';
    }
`

document.head.appendChild(style)

You can use a template literal to break your CSS into multiple lines for improved readability. Don't forget to actually append the element to your head after you created the CSS.

To add styles to elements in JavaScript, you can use:

  • element.style[property], eg.: element.style.color
  • element.style.cssText, eg.: 'color: yellow;'
  • A dynamically created style tag for global styles
  • A helper function for looping through object of styles
  • twitter
  • facebook
JavaScript
Did you find this page helpful?
πŸ“š More Webtips
Frontend Course Dashboard
Master the Art of Frontend
  • check Access 100+ interactive lessons
  • check Unlimited access to hundreds of tutorials
  • check Prepare for technical interviews
Become a Pro

Courses

Recommended

This site uses cookies We use cookies to understand visitors and create a better experience for you. By clicking on "Accept", you accept its use. To find out more, please see our privacy policy.