document.write is document.wrong - whenever you use it after the page has been loaded, it replaces the whole page with the new HTML string. That's pretty much never a good idea. In this case, it's replacing the page including your CSS, so there's no style to apply to the class1.
Use proper DOM methods instead:
function sayHi() {
const h1 = document.body.appendChild(document.createElement('h1'));
h1.className = 'class1';
h1.textContent = 'Goodbye!';
}
.class1 {
color: red;
font-size: 400%;
}
<h1 class=class1>Hello World</h1>
<button onclick="sayHi()">Click me</button>
Or, if you want to remove the existing elements first (but not the style), clear document.body:
function sayHi() {
document.body.textContent = '';
const h1 = document.body.appendChild(document.createElement('h1'));
h1.className = 'class1';
h1.textContent = 'Goodbye!';
}
.class1 {
color: red;
font-size: 400%;
}
<h1 class=class1>Hello World</h1>
<button onclick="sayHi()">Click me</button>
document.writeused that way (in an event) has side effects that result in the style being lost ... so ...document.writeis old old school, and should never be used, except maybe in inline code that runs during page load