There is a code:

body{ position: relative; } body::before { background-size: cover; content: ' '; height: 100%; left: 0; position: fixed; top: 0; width: 100%; will-change: transform; z-index: -1; } 

And css code:

  body.grad1 { background: radial-gradient(black 15%, transparent 16%) 0 0, radial-gradient(rgba(255, 255, 255, .1) 15%, transparent 20%) 0 1px; background-color: #12364a; background-size: 12px 12px; } 

I add this class when I click on the div in this way:

 document.body.classList.add('img6'); 

but it is added to the body and looks different in the end, but how to add it to body::before ?

  • one
    no way. HTML attributes cannot be added to pseudo elements - Jurij Jazdanov

1 answer 1

No HTML attributes cannot be added to pseudo elements. Alternatively, set a pseudo-element for the class and change the class of the element, with which the necessary pseudo-element will be used.

 function changeClass(elem) { document.body.classList.toggle('grad1'); } 
 body{ position: relative; } body::before { background-size: cover; content: ' '; height: 100%; left: 0; position: fixed; top: 0; width: 100%; will-change: transform; z-index: -1; } body.grad1::before { background: radial-gradient(black 15%, transparent 16%) 0 0, radial-gradient(rgba(255, 255, 255, .1) 15%, transparent 20%) 0 1px; background-color: #12364a; background-size: 12px 12px; } 
 <div id='elem' onclick='changeClass()'>Hello world!</div>