All Questions & AnswersCategory: Front-end QuestionHow can we create dynamic CSS classes in JavaScript?
Rajesh asked 3 years ago

How can we create dynamic CSS classes in JavaScript.

1 Answers
apporve answered 3 years ago

// I have a response object which has some color values, based on that values we have to create separated css classes.

createDynamicClass(response) {
        
    let style = document.createElement(‘style’);
    
    style.type = ‘text/css’;
    
    style.innerHTML = `.dy-action-btn-color { background-color: ${response.actionColor} !important; }
                        .dy-body-color { background-color:${response.bodyColor} !important; }
                        .dy-header-color { background-color: ${response.headerColor} !important; }
    `; // ` ` -> syntax is typescript syntax : you can use simple string concatenate.
    
    
    document.body.appendChild(style); // finally append in DOM
}

Your Answer