I have successfully developed a custom web component without using any framework. I then proceeded to populate it with content from a template tag.
Although I was able to manipulate the content using JavaScript, I encountered difficulties when trying to modify the styles dynamically through JavaScript. Can anyone explain why this is happening and provide guidance on how to edit CSS within a web component using code?
class GeneratorView extends HTMLElement {
connectedCallback() {
// Using a template to inject content into this component
const template = document.getElementById('generator-template')
const templateContent = template.content
this.appendChild(templateContent)
// Locating the label element inside this component
const label = this.querySelector("#label")
// THIS WORKS - changing the label text
label.innerText = "The updated text"
// THIS DOESN'T WORK - attempting to change the label style
label.style.border = "4px solid red;"
}
}
customElements.define('generator-view', GeneratorView)
The template structure resembles the following:
<template id="generator-template">
<div id="label">
Modify this text
</div>
</template>