Home > Mobile >  How do I programmatically change CSS class rules
How do I programmatically change CSS class rules

Time:11-09

I have the following CSS and need to programmatically update it after clicking a button but I cannot figure out how.

This is the initial CSS

.hoverable:hover {
  color: red;
}

I need the class to have the following CSS after clicking the button.

.hoverable:hover { 
  color: blue;
}

CodePudding user response:

You cannot modify style inside pseudo-class but you can change css variable.

const hoverable = document.querySelectorAll('.hoverable')

const button = document.querySelector('#button')

button.addEventListener('click', () => {
  hoverable.forEach((el) => {
    el.style.setProperty("--hoverColor", "blue")
  })
})
.hoverable {
  --hoverColor: red;
}

.hoverable:hover {
  color: var(--hoverColor);
}
<p >foo bar</p>
<p >foo bar 2</p>

<button id="button">press me</button>

CodePudding user response:

The easiest way would be to use document.querySelectorAll() and loop over the results. There are methods to change the CSSStyleRule object itself, but they are convoluted and hard to read.

document.getElementById('btn').addEventListener('click', () => {
  const els = document.querySelectorAll('.hoverable');
  for (const el of els) {
    el.style.color = 'blue';
  }
});
.hoverable {
  color: red
}
<p >Some text.</p>

<button id="btn">Click me</button>

  • Related