Custom component not rendering expected CSS style

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>

Answer №1

One issue you may encounter is the unnecessary use of a semicolon in your styling.

The semicolon is specifically used by the CSS parser to indicate breaks between CSS values. It is not required after the last value, and it should not be utilized when setting values within an element's style attribute.

I have simplified your code for clarity.

Including 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>

Excluding 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>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How can one properly conduct a health check on a Twilio connection using TypeScript?

How can I create an endpoint in TypeScript to verify if the Twilio connection is properly established? What would be the proper method to perform this check? Below is a snippet of my current code: private twilioClient: Twilio; ... async checkTwilio() { ...

Creating dynamic routes in express.js with fixed components

I'm exploring how to create a route in express that captures URLs like this: /events/0.json Here's what I've attempted so far (but it's not working as expected): router.put('/events.json/:id.json', isLogged, events.update) ...

Keep an eye on the syncing progress of pouchdb replication

What is the best way to alert the user if there is a loss of Internet connection or if the server goes offline, causing live sync to stop? var localdb = new PouchDB('localdb'); var remotedb = new PouchDB('http://localhost:5984/xyz&a ...

Attach the keyboard to the screen in a fixed position

How can I keep the keyboard always visible on the screen? The screen contains: one TextInput (multiline) two FlatList Typing in the TextInput is fine, but when interacting with the FlatList, the keyboard disappears. I want the keyboard to remain visib ...

Disabling Scrolling in AngularJS Material Tab Components

I'm experimenting with AngularJS Material components and struggling with creating tabs. Every time I add a tab, the content inside the child md-content element automatically gets a fixed height with a vertical scrollbar instead of adjusting its heigh ...

Tips for properly executing directives in sequential order while using async in Angular 13

I created a standard registration form using Angular and implemented an async directive (UserExistsDirective) to validate if the email is already taken. To manage error messages, I also utilized a second directive (ValidityStyleDirective) which is also use ...

Tips on setting up a dropzone upload feature with a click-trigger option

Is there a way to configure dropzone.js so that the file is uploaded only when a submit button is clicked, rather than automatically? Here's the code snippet I am currently using: $('#myDropzone').dropzone({ url: SITE_URL + 'self_r ...

Creating HTML elements dynamically with attributes based on the `as` prop in React using TypeScript

Is there a way to dynamically create HTML elements such as b, a, h4, h3, or any element based on the as={""} prop in my function without using if guards? I have seen a similar question that involves styled components, but I am wondering if it can be done ...

Is there a CSS3-compatible CSS parser available in C/C++?

Are there any C/C++ CSS parsers that currently support CSS3? I have come across a few, but none of them seem to offer full CSS3 compatibility. ...

Unable to attach numerous parameters to the content of the request

I am encountering an issue with my code where I have two classes and need to call two separate models using two store procedures to insert data into both tables. The controller is set up like this: [HttpPost] public IHttpActionResult AddData([FromBody]ILi ...

Element in the Middle

I have just started learning HTML and CSS, and I'm curious to know how I can center the links Home, About, and Contact in the header. HTML: <body> <header> <h1><a href="#">HBT</a> </h1& ...

Issue with custom font display malfunction

I'm having difficulty getting my custom @font-face to function properly. When I apply this class style to a <p>, it always defaults to Arial. Can anyone point out what might be going wrong here? <style> .stonefont @font-face { font-fa ...

Formatting HTTP HTML response in Vue.js can be achieved by utilizing various methods and techniques

I have a WordPress site and I'm trying to fetch a specific post by its ID. Currently, the content is being displayed successfully, but it's also showing HTML tags in the main output. Here is an example: https://i.stack.imgur.com/f3pdq.png Code ...

What is the best way to use command line arguments within a Node.js script?

As a newcomer to the world of programming, I find myself struggling to make progress despite putting in significant effort. Although it may seem like a trivial question, my lack of progress is becoming frustrating. Currently, I am working on a node.js scr ...

Ways to center align text in a div vertically

I'm working with 2 divs that are floating side by side. The left div contains a part number, which is only one line. The right div holds the product description, which can span multiple lines. I am looking for a way to vertically align the text in t ...

Navigate to the logout page upon encountering an error during the request

I recently upgraded our application from angular 2 to angular 5 and also made the switch from the deprecated Http module to the new HttpClient. In the previous version of the application, I used the Http-Client to redirect to a specific page in case of er ...

The error message stating that property 'catch' does not exist on type 'Observable<IEmployee[]>' cannot be fixed by simply adding the import 'rxjs/add/operator/catch'

When I hover over .catch(this.errorHandler), an error message is displayed Property 'catch' does not exist on type 'Observable'.ts(2339) I am unable to import the catch function into Angular Typescript. Upon hovering over .catch(th ...

Nested ui-view is not appearing as expected

I have a query about Angular UI-Router and its ui-views functionality. I am facing an issue where only the ui-view with the name "languages" is displaying, despite declaring three ui-views inside another one. Any assistance in resolving this would be highl ...

Handling Firebase callbacks once the save operation is completed

Currently using AngularFire with Firebase. Unfortunately, still stuck on Angular 1 :-( I'm curious if there's a method to set up a callback function that triggers every time data is successfully saved in the database. I am aware of the option to ...

Run HTML/Angular ng-include with JavaScript

I am developing a small search app using AngularJS. I have an empty div that I want to replace with another div containing ng-include after running a function. The replacement of the div works fine, but ng-include does not load properly. For testing purpo ...