Search code examples
javascripthtmlcssstyles

How to add CSS properties with JavaScript without style attributes


I am creating custom HTML tags. I want to know if was possible to add CSS properties to HTML tags with JavaScript without adding, use css file or appear the "style" attribute on the HTML tag, example:

NO:

<-my-tag style="color:red">STACKOVERFLOW</-my-tag>

YES:

<-my-tag>STACKOVERFLOW</-my-tag>

And the result like this


Solution

  • You can create a style element in DOM and append anything to it which will automatically apply to your element

    const appendStyle = (customStyles) => {
        const styleEl = document.createElement('style');
        styleEl.innterHTML = `yourTagName {${customStyles}}`;
        document.body.appendChild(styleEl);
    }
    
    appendStyle('background-color: red; font-size: 15');