简体   繁体   中英

CSS Style not applied on custom component

I created a custom web component (without any framework). Then I fill it with content from a template tag.

Finally, I edit the content using Javascript. This works fine. What doesn't work is editing the styles using Javascript. Why is this, and how can I edit the CSS inside a web-component using code?

class GeneratorView extends HTMLElement {

    connectedCallback() {

        // Use a template to fill this component
        const template = document.getElementById('generator-template')
        const templateContent = template.content
        this.appendChild(templateContent)

        // find the label tag in this component
        const label = this.querySelector("#label")

        // THIS WORKS - set the label text
        label.innerText = "The text has changed"

        // THIS DOESN'T WORK - set the label style
        label.style.border = "4px solid red;"
    }
}

customElements.define('generator-view', GeneratorView)

The template looks something like this

<template id="generator-template">
        <div id="label">
            Change this text
        </div>
</template>

The problem is you are adding a semicolon to your style.

The semicolon is only used by the CSS parser to know the breaks between then css values. You do not need one after the last value and you can not use them when setting a value in an element's style attribute.

I simplified your code to demonstrate.

With the semicolon

 const template = `<div id="label">Change this text</div>`; class GeneratorView extends HTMLElement { connectedCallback() { this.innerHTML = template; const label = this.querySelector("#label"); label.innerText = "The text has changed"; label.style.border = "4px solid red;" } } customElements.define('generator-view', GeneratorView);
 <generator-view></generator-view>

Without the semicolon

 const template = `<div id="label">Change this text</div>`; class GeneratorView extends HTMLElement { connectedCallback() { this.innerHTML = template; const label = this.querySelector("#label"); label.innerText = "The text has changed"; label.style.border = "4px solid red"; } } customElements.define('generator-view', GeneratorView);
 <generator-view></generator-view>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM