-1

let us assume that i want to change the color of text given to element through css class. i want to change color from white to red. Please give answer in pure javascript my css code is like

.input {
background-color: black;
color:white;
}

2 Answers2

2

Unclear if you want to modify the css rule... but here is a way to manipulate the css using javascript

for (let style of document.styleSheets) {
  for (let rule of style.rules) {
    if (rule.selectorText === '.input') {
      rule.style.color = 'blue'
    }
  }
}
.input {
  color: red;
}
<p class="input">hello world</p>
Endless
  • 34,080
  • 13
  • 108
  • 131
  • An easier way would have been to use [css variables](https://developer.mozilla.org/en-US/docs/Web/CSS/Using_CSS_custom_properties) – Endless Sep 07 '20 at 12:56
0

Get a list of all elements which use your class and modify their properties:

var elements = document.getElementsByClassName("input");
for(var i = 0; i < elements.length; i++) {
    elements[i].style.color = "red";
}
JKD
  • 1,279
  • 1
  • 6
  • 26