Applying CSS styles to a class dynamically using JavaScript

Is there a way to dynamically add a new CSS property to an existing class using JavaScript?

Let's say I have a class called .test with some pre-defined styling. How can I append the property color: blue; to this class using JavaScript?

const elm  = document.querySelector('.test');
.test {
  width: 200px;
  height: 50px;
  background-color: orange;
}
<div class="test">Testing...123</div>

Answer №1

If you're looking to locate a specific CSS rule with the selector of .test and then apply additional properties to it, follow these steps:

let target;

outer: for(let sheet of document.styleSheets) {
  for(let rule of sheet.rules) {
    if(rule.selectorText === '.test') {
      target = rule;
      break outer;
    }
  }
}

if(target) {
  target.style.backgroundColor = 'green';
}
.test {
  font-size: 16px;
  line-height: 1.5;
  color: #333;
}
<div class="test">Example text</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

Error: Compilation was unsuccessful due to module not found. Unable to resolve in ReactJS

As I was wrapping up this task, an unexpected error popped up: Module not found: Can't resolve './components/Post' in ./src/pages/index.js I've tried everything to troubleshoot it but no luck. Here's a rundown of my code snippets ...

Call a React component from an external JavaScript file

I am working on a react application that has a bundle.js file created using webpack containing all the necessary code. Recently, I started developing a separate dotnet application and I need to display the main 'App' component from my react appl ...

Retrieving a JavaScript variable from a different script file

I have a JavaScript script (a) with a function as follows: function csf_viewport_bounds() { var bounds = map.getBounds(); var ne = bounds.getNorthEast(); var sw = bounds.getSouthWest(); var maxLat = ne.lat(); var maxLong = ne.lng(); ...

Having trouble accessing the initial two elements of an array while generating a Fibonacci series in JavaScript

Attempting to generate a Fibonacci sequence that always starts with [0, 1] using basic JS has proven challenging. The current implementation of the function does not properly return the first two items in an array when calling the corresponding n number. F ...

Angular 6: Simplify Your Navigation with Step Navigation

Can someone please assist me with configuring a navigation step? I tried using viewchild without success and also attempted to create a function with an index++ for three components on the same page. However, I am unable to achieve the desired outcome. Any ...

How to integrate a jQuery plug-in into your Meteor 1.7.0.3 project

Recently, I delved into using Meteor for the first time, and it has been about a week since I started exploring its functionalities. However, I encountered an issue with integrating jQuery plugins that were installed via npm. After running: meteor npm i ...

Displaying content on a click event in AngularJS

I am facing an issue with the ng-show directive not working as expected when a user clicks on an icon. The desired behavior is that the parent div should initially display content, but when the play icon is clicked, the contents of the div should become ...

Tips for updating or replacing items in a JavaScript array

Explaining what I need, here's the code snippet: Everything works smoothly when adding a product to the items array if it does not already exist (based on id). However, if it does exist, I only want to update the item. The distinction is based on the ...

Unable to open a modal in Angular UI after closing the initial modal

Hey there! I've been attempting to open a modal after closing the first one, but I'm encountering an issue where the second modal appears to be opened but is actually not. I'm struggling to understand what's causing this problem. Could ...

When the Next js page loads, it briefly displays a 0 at the top for a moment before loading the rest

When my nextjs app loads a page, there is a momentary appearance of a 0 in the top left corner. This happens even if I am fetching data from Sanity CMS using getStaticProps and returning content. Interestingly, I have observed that simply returning an empt ...

Changing a variable with Functions and Objects

I'm curious to know what the index variable returns in this code snippet. I believe it will be 0. function jsTest() { var index = 0; var counter = 0; var obj = {}; obj.index = index; var func = function () { for (index ...

After the upgrade from Angular 5.2 to Angular 6, Bootstrap 4 dropdown and Bootstrap-select dropdown seem to have lost their dropdown functionality. This issue arose after updating to Bootstrap 4 and jquery

Update: Upon further investigation, I experimented with a standard Bootstrap 4 dropdown and encountered the same issue – it would not open. This leads me to believe that the problem may not be specific to the selectpicker class or the bootstrap-select de ...

The function slice is not a method of _co

I'm attempting to showcase the failedjobs array<any> data in a reverse order <ion-item *ngFor="let failjob of failedjobs.slice().reverse()"> An issue arises as I encounter this error ERROR TypeError: _co.failedjobs.slice is not a fu ...

Which Browser (or version) is the Only One That Cannot Manipulate Flash Objects?

In my attempts to modify Flash Objects / Embeds using Javascript, I've found that it works in all browsers except for IE. This has led me to consider abandoning IE altogether for this application, unless there are other older or less used browsers tha ...

Create a new object by extracting JSON data using JavaScript

I am attempting to extract various data elements from a JSON file and place them into an object. My ultimate goal is to then convert this object back to JSON format, containing only the desired data. I believe that structuring the object like this might w ...

JavaScript - Issues with Cookie Setting

I created a function for setting cookies: function storeCookie(cname, cvalue, exdays){ var d = new Date(); d.setTime(d.getTime() + (1000*60*60*24*exdays)); var expires = "expires="+d.toGMTString(); document.cookie = cname + "=" + cvalue + ...

"Protractor encountered an issue when navigating to the most up-to-date Angular section in our

We are in the process of upgrading our application from AngularJS to the latest version of Angular. I am currently working on writing tests that transition from the AngularJS version of the app to the admin application, which is built using the latest ver ...

Is there a way to create an event listener that responds to a simultaneous click of both mouse buttons?

Despite my extensive research on the Internet, I was unable to find any examples. Interestingly, Vue only supports right and left clicks separately which I find peculiar as it seems like a basic task that can easily be accomplished with plain Javascript. ...

Maximizing the potential of selectors in jquery.min.js

Can anyone explain what the purpose of selectors = {cacheLength: is in the jquery.min.js file? Additionally, I'd like to know if it is feasible to modify the value of cacheLength using jQuery. =ga.getText=function(a){var b,c="",d=0,f=a.nodeT ...

Guide on linking a textarea with a boolean value in the child component

I have created a form component consisting of two components. The first component looks like this: <template> <div class="flex flex-col items-center justify-center gap-2"> <div class="flex w-[80%] items-center justify-ce ...