0

is it possible to append new class with some CSS rules to an element, for example a div, and add this class to style section?

For example, when user clicks on a button I want to add new class 'newClass' with CSS background-color: red for my div element, and append

.newClass{
background-color: red
}

to my <style> section. Thanks for the help!

Ulysse BN
  • 10,116
  • 7
  • 54
  • 82
Pat
  • 117
  • 1
  • 9

2 Answers2

2

You can use CSSStyleSheet.insertRule

 var styleEl = document.createElement('style');

  // Append style element to head
 document.head.appendChild(styleEl);

  // Grab style sheet
 var styleSheet = styleEl.sheet;
 myStyle.insertRule(".myClass { color: red }", 0);

Read more here

So to do it with your button do:

$('#myButton').click(function(){
   var styleEl = document.createElement('style');
   document.head.appendChild(styleEl);

   var styleSheet = styleEl.sheet;
   myStyle.insertRule(".myClass { color: red }", 0);
});
LiefdeWen
  • 586
  • 2
  • 14
0

try this code , this is written whit vanilla javascrit , if you write it with jq it would be better, but it is works

function changeClass(){
  document.getElementById('asdf').className += " newClass";
}
<style>
    .newClass {
        background-color: red
    }
</style>
<div id='asdf'>
    aaaa
</div>
<button onclick=changeClass()> click</button>
eborrallo
  • 750
  • 1
  • 8
  • 17