typescript is failing to update CSSRule with the newly assigned background-color value

I am currently working on dynamically changing the CSS style (specifically background-color) for certain text on a webpage. To achieve this, I have been attempting to modify CSSRule by accessing the desired CSSRule based on selectedText. Here is the code snippet:

  changeRule() {
    let stylesheet: CSSStyleSheet = <CSSStyleSheet>this.stylesheet.sheet;
    let ruleLength: any = <CSSStyleSheet>this.stylesheet.sheet.cssRules.length;
    console.log(ruleLength)
    for(let i = 0; i < ruleLength; i++) {
      let currentTag: any = this.stylesheet.sheet.cssRules[i].selectorText as CSSStyleSheet
      let chosenTag: any = (`#text `+`[data-tag-id="${this.selectedTag.id}"]`)
      if(currentTag === chosenTag) {
        console.log("Rule matched");
        console.log(<CSSStyleSheet>this.stylesheet.sheet.cssRules[i].style.backgroundColor);
        let changedTag: any = <CSSStyleDeclaration>this.stylesheet.sheet.cssRules[i].style.backgroundColor
        changedTag = "initial";
        break;
      }      
    }
    console.log(<CSSStyleSheet>this.stylesheet.sheet)
  }

However, despite running this function, the corresponding CSSRule does not seem to be updated with the new BackgroundColor. Furthermore, I am encountering a compile time error related to cssRules[i] stating that "Property cssRules does not exist on type StyleSheet". It's worth mentioning that I am using angular2 with typescript.

If anyone has any suggestions or insights on how to tackle this issue, please feel free to share them with me!

Answer №1

To update the rule property instead of the variable, make the following change:

<CSSStyleDeclaration>this.stylesheet.sheet.cssRules[i].style.backgroundColor = "initial";

Here's a JavaScript example (using "yellow" in place of "initial"):

function changeRule() {
    let stylesheet = this.stylesheet.sheet;
    let ruleLength = this.stylesheet.sheet.cssRules.length;
    console.log(ruleLength);
    for (let i = 0; i < ruleLength; i++) {
        let currentTag = this.stylesheet.sheet.cssRules[i].selectorText;
        let chosenTag = (`#text ` + `[data-tag-id="${this.selectedTag.id}"]`);
        if (currentTag === chosenTag) {
            console.log("Rule matched");
            console.log(this.stylesheet.sheet.cssRules[i].style.backgroundColor);
            this.stylesheet.sheet.cssRules[i].style.backgroundColor = "yellow";
            break;
        }
    }
    console.log(this.stylesheet.sheet);
}
setTimeout(changeRule.bind({
  stylesheet: {
    sheet: findSheet()
  },
  selectedTag: {
    id: "foo"
  }
}), 1000);
// In case stack snippets move the sheet around:
function findSheet() {
  var sheets = Array.prototype.slice.call(document.styleSheets);
  var sheet;
  sheets.some(function(s) {
    if (s.cssRules[0].selectorText == '#text [data-tag-id="foo"]') {
      sheet = s;
      return true;
    }
  });
  return sheet;
}
#text [data-tag-id="foo"] {
  color: red;
  background-color: grey;
}
<div id="text">
  <div data-tag-id="foo">This is foo</div>
  <div data-tag-id="bar">This is bar</div>
</div>

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

Ways to troubleshoot and verify values in PHP that are sent through AJAX

In my jQuery function, I am using AJAX to send values to a PHP file: $.ajax({ //make ajax request to cart_process.php url: "cart_process.php", type: "POST", dataType: "json", //expect json value from server data: { quantity: iqty, ...

Updating the jQuery AJAX URL dynamically based on user input in a form submission

Exploring the world of AJAX and form submission, I find myself in need of assistance. My webpage is designed to display real-time stock market data, updating fields with the latest price, change, high, low, and more. I am currently attempting to modify th ...

Having trouble invoking the child component when the button is clicked

I am utilizing the ng-sidebar library. My goal is to trigger a child component (sidebar) when a button is clicked, but I am unable to achieve the desired result. For example: Check out this Stackblitz demo Parent TypeScript code: export class AppComponen ...

Preventing browser flickering when using 'loadURL' to switch between URLs in Electron

Within my electron app, I am utilizing a singular window. As users navigate through the various "forms" within the application, I make use of the mainWindow.loadURL('file://...') function. Unfortunately, this approach leads to a flashing effect w ...

Calculate the total with the applied filters

My goal is to sum the data from the Number table after applying lookup filters. The current issue is that the sum remains fixed for all values and doesn't take into account the filter. Here's the JavaScript function I'm using to search and ...

What is the best way to prevent the output folder from appearing in the import statements for users of my package?

I have a project written in Typescript that consists of multiple .d.ts files. I would like to package this project as an npm module and utilize it in another project. In the second project, my goal is to be able to import modules like so: import {Foo} fr ...

Run XQuery dynamically in JavaScript and store the outcome in a JavaScript variable

Looking to achieve the following: Running a dynamic XQUERY stored in a JavaScript variable example var myxquery = For Channels.Channel where Channel/availability = yes And Channels.Channel/Label = 'CNN' Return EXIST(Channels.Channel/Id)&apo ...

Arrange the div and ensure that the external JavaScript file functions properly when the page loads

I am encountering an issue with my JavaScript and CSS code. It works perfectly fine within the fiddle environment but fails to function properly outside of it. Here is the link to the fiddle When I embed the code into an HTML document directly, it does n ...

In PHP/HTML, input submit does not work with CSS styling

I am struggling with styling the input submit button in my form. I want the button to appear as text with a change in background and font color on hover. Any solutions? input[type="submit"] { font-family: made, mirage; text-decoration: none; backg ...

Guide on incorporating a dropdown menu within a Jssor slider

I am facing an issue with trying to include a dropdown menu inside the Jssor slider. The menu does not drop down when placed inside it. Here is the code snippet: <head> <script src="jquery.js"></script> <script src="jssor.slider.min. ...

Form submission not being recognized by Ajax's .done() function

I'm trying to include a form from another file using ajax. It's a simple form that is activated by an onclick event defined as follows: <a href="javascript:void(0);" class="remitir" title="Reemitir Solicitud" data-id="'.$value['idso ...

Problem with Angular2 app routing on the github pages

As a newcomer to Angular2, I am in the process of setting up a small Angular2 app (helloworld) on github pages to kickstart my project. I initially created ng2-lite with the help of angular-cli, and it is now hosted at this site. The deployment was handle ...

Adjustable CSS display: an adaptable left column paired with a changeable fixed right column

I am looking to align the content of a div element in a single row while dealing with an unknown width of the ul element due to varying child li elements. The h2 will always take up the remaining space, and each li element has a width of 20px. The desired ...

Display customizable template according to variable

The answer provided for the issue regarding dynamic template generation based on value instead of variable in this thread was really helpful. However, I'm facing challenges in getting it to work. Here's a simplified example: export class A { } ...

Troubleshooting Vue.js dynamic image path loading issues

Struggling to dynamically load images in a single file component, I keep encountering an error stating that the module cannot be found. It seems like I'm attempting something similar to what was discussed in this post on Stack Overflow, but I can&apos ...

What is the best way to display text from one text field onto another text field?

Here's a challenging question that I've been pondering... Issue: I am using a virtual keyboard that needs to interact with different text fields on various pages. Every time I click on a text field, the keyboard should appear, and every key I pr ...

Add a directive on the fly, establish a connection, and display it dynamically

Within my markup, I have a tag element called popup-window which is handled by a specific directive. If I wish to incorporate multiple similar widgets that can be displayed or hidden in various locations, I currently need to include all these elements dire ...

AngularJS flip card animation

Exploring the new AngularJS method for animations during page transitions, I am keen on integrating a card flip effect (resembling http://jsfiddle.net/nicooprat/GDdtS/) body { background: #ccc; } .flip { -webkit-perspective: 800; width: 400px; height: ...

What is the method for executing a for loop in AngularJS without relying on HTML elements?

I'm creating an application in AngularJS where the structure requires me to execute a for each loop without using any HTML elements or div tags with ng-repeat. In Django, we typically use the following syntax: {% for item in list %} {{ item }} {% ...

Submit a data array using formData through axios

I am planning to send array data using formData. The backend is set up to accept the data array separated by a dash ; For example, if I were to use Postman and input the form-data like this: id_barang : 122;288;383 (sending 3 values of id with dashes ;) W ...