A: the preface

In Web applications, we often need to dynamically control CSS styles to enrich our pages. How much do you know about these native style operations in this era of frameworks?


Element.className: A DOMString representing the class of this Element. Multiple classes are separated by Spaces.

If we have an element whose outerHTML is

then the element’s className value is’ Demo active red’.

If we use this method for element class management, it is not a good way, because it involves a lot of string cutting, concatenation, deletion operations. Next, I will use class add, remove, and replace to briefly demonstrate:

/** * remove class *@param elem- The element that requires class operation *@param token- The class name to be removed */
function removeClass(elem: Element, ... tokens:string[]) {
  const temp = elem.className.split(/\s+/).filter((token) = >! tokens.includes(token)) elem.className = temp.join(' ')}/** * add class *@param elem- The element that requires class operation *@param token- Name of the class to be added */
function addClass(elem: Element, ... tokens:string[]) {
  const temp = new Set([...elem.className.split(/\s+/), ...tokens])
  elem.className = [...temp].join(' ')}/** * replace class *@param elem- The element that requires class operation *@param oldToken- Replaced class name *@param newToken- Alternate class name */
function replaceClass(elem: Element, oldToken: string, newToken: string) {
  const names = elem.className.split(/\s+/).filter((token) = >token ! == oldToken) names.push(newToken) elem.className = names.join(' ')}Copy the code

Of course, element. className = ‘XXX XXX’ is equivalent to element. setAttribute(‘class’, ‘XXX XXX ‘), Similarly, const className = element. className is equivalent to const className = element.getAttribute (‘class’).


Element.classList: Returns the class attribute that this Element contains, which is a DOMTokenList.

ClassList is the easiest and most efficient way to manipulate classes, because it has a rich BUILT-IN API for class manipulation.

Take add, remove, and replace for example:

// <div class="demo active red"></div>
const elem = document.querySelector('.demo')

// addClass
elem.classList.add('bgcolor')  // <div class="demo active red bgcolor"></div>

// removeClass
elem.classList.remove('demo')  // <div class="active red bgcolor"></div>

// replaceClass
elem.classList.replace('active'.'focus')  // <div class="focus red bgcolor"></div>
Copy the code

In addition to these three methods, classList also has a rich API for us to use. For details, see MDN.


Htmlelement. style: Gets/sets the style attribute of an element, which is a CSSStyleDeclaration.

Up to now, are there students using getAttribute and setAttribute style management? If so, that means you’re doing a lot of unproductive work, just like you’re using classNames for class management with classList.


First let’s look at the more general htmlelement. style usage:

< / div >
const elem = document.querySelector('#demo') // getter const color = elem.style.color const bgcolor = elem.style.backgroundColor // Style names separated by "-" are changed to "little hump" // setter elem.style.color = '#FFFF00' //
< / div >
// remove elem.style.height = null //
< / div >
elem.style.color = ' ' //
< / div >
Copy the code

This getter/setter approach already works for most of our scenarios, but if you want to use it for a style! When the important modifier is used, you will find that the setter is invalidated:

In this particular case, do you think we’re going to go back to setAttribute management? You don’t have to; CSSStyleDeclaration provides us with an API to handle various requirements.


< / div >
const elem = document.querySelector('#demo') // getter const color = elem.style.getPropertyValue('color') const bgcolor = elem.style.getPropertyValue('background-color') // setter elem.style.setProperty('color'.'#FFF000') //
< / div >
elem.style.setProperty('color'.'#FFFF00'.'important') //
< / div >
// remove elem.style.removeProperty('color') //
< / div >
elem.style.setProperty('height'.null) //
< / div >
elem.style.setProperty('background'.' ') //
Copy the code


Htmlstyleelement. sheet: that is,

HTMLStyleElement is basically a

You might have “


At this stage, if we want to control the CSS style dynamically, we can only do raw string manipulation, but we need to note that we can only write CSS styles with

If we do an assignment with


When the return value of

Modify style rules

To modify an existing style under a

Cssstylesheet. cssRules: Returns a real-time CSSRuleList containing an up-to-date list of the CSSRule objects that make up the stylesheet.

In fact, CSSRuleList is a real-time style list composed of CSSStyleRule. CSSRule is just an interface, and CSSStyleRule is a concrete implementation of the CSSRule interface.

CSSStyleRule: Represents a CSS style rule. It implements the CSSRule interface.

So let’s take a look at CSSStyleSheet. CssRules. What does it look like?

CSSStyleRule. Style is a CSSStyleDeclaration object, just like htmlElement. style.

Note: Changing the

Add/remove style rules

Added: cssStylesheet.insertrule (cssText[, index]) : Inserts a new rule at a specific location in the stylesheet, requiring the full text of the new rule.

Delete: cssStylesheet.deleterule (index) : Deletes a rule at a specific location from the stylesheet.

/*  */
const style = document.querySelector('#demo')
const sheet = style.sheet as CSSStyleSheet

// Add style rules
sheet.insertRule('.box { border: 1px solid #999; } ')  // Add to the end
sheet.insertRule('.box { padding: 10px 15px 5px; } ', sheet.cssRules.length)  // Add to the end

// Delete the style rule
sheet.deleteRule(sheet.cssRules.lenght - 1)  // Delete the last rule
Copy the code

Note: cssText is a complete CSS rule, including selectors and style declarations. Index Range 0 ≤ index ≤

For those of you interested in htmlStyleElement. sheet, take a look at the file interim.

Six: conclusion

With the exception of htmlStyleElement. sheet, all of the previous ones have been used to some extent, but perhaps not in such detail. So are there any application scenarios where htmlStyleElement. sheet is so blatant? There are, for example, rich text editor selection and rich text editor find and replace highlighting.

Personal feeling, these operations in the article in addition to do native development, basic are not used!

Note: in the process of writing this article, part of the page of MDN website suddenly cannot be opened, which also leads to some keywords in the article did not add related links, some links added may not be opened…… Forgive me,