Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

Eugene Karataev
Eugene Karataev

Posted on • Edited on

     

Javascript Set CSS Set CSS styles with javascript

Let's say you have a paragraph.

<pid="target">rainbow 🌈</p>
Enter fullscreen modeExit fullscreen mode

And you need to change it's color with JS. What options do you have?

1. Inline styles

The most straightforward path. Query the element from DOM and change it's inline styles.

document.getElementById('target').style.color='tomato';
Enter fullscreen modeExit fullscreen mode

inline styles

Short and simple.

2. Global styles

Another option is to create<style> tag, fill it with CSS rules and append the tag to the DOM.

varstyle=document.createElement('style');style.innerHTML=`  #target {  color: blueviolet;  }  `;document.head.appendChild(style);
Enter fullscreen modeExit fullscreen mode

global styles

3. CSSOM insertRule

Third option is less known. We gonna useCSSStyleSheetinsertRule method.

varstyle=document.createElement('style');document.head.appendChild(style);style.sheet.insertRule('#target {color: darkseagreen}');
Enter fullscreen modeExit fullscreen mode

While it might look similar to the 2nd option, it's definitely different.
insertRule

As you can see in Chrome devtools,<style> tag is empty, but the style (darkseagreen color) is applied to the element. Also the color can't be changed via devtools because Chrome doesn't allowediting dynamic CSS styles.

Actually such behavior was the motivation to write this post. A popular CSS-in-JS libraryStyled Components use this feature to inject styles in production mode because of performance. This feature might be undesirable in specific projects or environments and some folks complain about it in the project's issues.

4. Constructable Stylesheets (July 2019 update)

It's now possible to createCSSStyleSheet object from JavaScript.

// Create our shared stylesheet:constsheet=newCSSStyleSheet();sheet.replaceSync('#target {color: darkseagreen}');// Apply the stylesheet to a document:document.adoptedStyleSheets=[sheet];
Enter fullscreen modeExit fullscreen mode

More details arehere.
This option is only valid for Chrome, so use with caution.

Do you know other options to add styles with javascript? What is your preferred option these days?

Thanks for reading!

Top comments(14)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss
CollapseExpand
 
mzahraei profile image
Ardalan
  • Education
    Software technology
  • Work
    - at -
  • Joined
• Edited on• Edited

hey can you maybe help me ?
I have some things like this and I just want to Update the hidden class but I Update Complete Style

<style>    .hidden{         animation-name: bgshower;        animation-duration: 2s;        position: absolute;        z-index: 2;    }    .neopa{        background-color: darkred;        font-size: large;    }</style>
Enter fullscreen modeExit fullscreen mode

var style = document.getElementById('style');
var counter = parseInt(60);

        style.innerHTML = `        .bghidden {            height: 100%;            width: 100%;            background-color: #E96565;            top: 0;            left: 0;            `+ 'animation-duration:' + counter + "s" + `;            animation-name: bgshower;            animation-delay: 0s;            position: absolute;            z-index: 2;        }        `;        document.adoptedStyleSheets = [style];
Enter fullscreen modeExit fullscreen mode
CollapseExpand
 
karataev profile image
Eugene Karataev
undefined is not a function
  • Location
    Russia, Novosibirsk
  • Joined

I'm not 100% sure what you're trying to achieve, but if you need to add animations on an element(s) with JS after some event, consider the following way:

  • Define styles with css like
.hidden{...}.animate{...}
Enter fullscreen modeExit fullscreen mode
  • Add/remove CSS classes with animations when necessary with DOM API:document.querySelectorAll('.hidden').classList.add('animate')
CollapseExpand
 
mzahraei profile image
Ardalan
  • Education
    Software technology
  • Work
    - at -
  • Joined

Thanks for writing but I just wanted to update an element's CSS with JS.
no more new class I wanted to Edit animation-duration value from JS.
I resolve it thx

CollapseExpand
 
yellow1912 profile image
yellow1912
  • Joined

With CSSStyleSheet, what is the best way to replace a rule? I see insertRule seems to take an index, if I re-use that same index then that rule will be replaced? The reason is that I want to allow the endusers to change some styles via a UI, then quickly update that to the specific element.

CollapseExpand
 
freq32 profile image
freq32
Human
  • Location
    Los Angeles
  • Work
    Full Stack Dev at Freelance
  • Joined

3 veeery interesting. thanks for the tip ;)

CollapseExpand
 
marlo22 profile image
marcin93
I'm here to share my knowledge with you and improve my English skills. If you see that I made a mistake somewhere, I will be happy if you let me know about it. :)
  • Location
    Warsaw, Poland
  • Work
    Front-end developer
  • Joined
• Edited on• Edited

It's something I'm looking for. Thanks a lot!

CollapseExpand
 
smz_68 profile image
Ardalan
hey there,unfortunately it is not possible for me to write new post due to website policiy.
  • Location
    hey there, unfortunately it is not possible for me to write new post due to website policiy.
  • Joined
• Edited on• Edited

really great post i like it

CollapseExpand
 
codemilli profile image
Jooyoung Moon
Founder of Honmonos
  • Location
    Seoul
  • Work
    FE Developer at Naver
  • Joined

Hi :D
I just wondered if using insertRule for performance or not and I found this article. Thanks !

But how it differ?

CollapseExpand
 
karataev profile image
Eugene Karataev
undefined is not a function
  • Location
    Russia, Novosibirsk
  • Joined

I don't think you ever need to useinsertRule in your day-to-day job unless you hit some performance bottleneck when working with styles.
I think optimizations withinsertRule are useful for libraries (likestyled-components), but add unnecessary complexity when developing regular websites or apps.

CollapseExpand
 
xgqfrms profile image
xgqfrms
web full stack developer
  • Location
    UFO
  • Education
    Ph.D
  • Work
    SE at Google
  • Joined
CollapseExpand
 
xgqfrms profile image
xgqfrms
web full stack developer
  • Location
    UFO
  • Education
    Ph.D
  • Work
    SE at Google
  • Joined

style.setContent bug ❌

conststyle=document.createElement(`style`);// this.shadowRoot.appendChild(this.templateContent);// log(`this.shadowRoot`, this.shadowRoot);style.setContent=`      .run {        width: 100px;        height: 100px;        background: url(https://www.boston.com/wp-content/uploads/2016/05/yuge_anger.png) 0 0;        animation: run 500 step(6) infinite;      }      @keyframes run {        from {          background-position: 0 0;        }        to {          background-position: -600px 0;        }      }    `;
CollapseExpand
 
zouhair_sahtout profile image
Zouhair Sahtout
I am a Web Full Stack Developer and designer based out of Rabat, MA. I love building apps that solve real-world problems, and that are delightful to use.My specialities include JavaScript, React JS
  • Location
    Rabat, MA
  • Education
    OFPPT
  • Work
    Self Employed
  • Joined

Thanks man for sharing, I was looking for something like this long ago

CollapseExpand
 
mzahraei profile image
Ardalan
  • Education
    Software technology
  • Work
    - at -
  • Joined

great

CollapseExpand
 
nagarjundeepak profile image
Nagarjun
Fullstack Web Application dev, React JS & Node JS part time Tensorflow explorer
  • Location
    India
  • Work
    Frontend Developer
  • Joined

this is really helpful :)

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

undefined is not a function
  • Location
    Russia, Novosibirsk
  • Joined

More fromEugene Karataev

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp