What is the best way to generate similar CSS classes?

Similar Question:
How can I dynamically generate a CSS class in JavaScript and apply it?

I am looking to generate CSS classes based on the width specified by the user in a text field. While I know this can be achieved using inline styles, I prefer to avoid that due to the complexity of handling multiple properties. In this case, "width" serves as an example.

For instance, if the user enters a width of "20", I would like to have:

.w20 {width: 20px}

If the user specifies "21", then I want:

.w21 {width: 21px}

And so forth...

JSFIDDLE LINK

Thank you.

Answer №1

To dynamically add CSS rules directly to your stylesheets, you can utilize the document.stylesheets property.

styleSheet = document.styleSheets[0];
// It might be helpful to include a check for undefined here
styleSheet.addRule(selector, style);

For more information on how to use insertRule, or you can refer to the documentation for addRule.

You can also create a new style element:

var style = document.createElement('style');
style.type = 'text/css';
style.innerHTML = '.class { rules }';
document.getElementsByTagName('head')[0].appendChild(style);

Answer №2

To dynamically add CSS to your stylesheets, consider using the document.styleSheets property.

const stylesheet = document.styleSheets[0];
stylesheet.addRule(selector, style);

Another option is to use inline styles, which I highly recommend.

If you want to adjust the width of an element using JavaScript, you can do so with this code snippet.

element.style.width = "100px";

For those utilizing jQuery:

$("#selector").css("width", "100px");

Answer №3

Check out this link to discover how to dynamically add CSS rules.

In my view, with solid software design, there should be no need for such actions.

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

The "this" keyword is not defined in React Native

When I tried to use this.props.navigation.navigate(), I encountered an error message stating that it was undefined. After researching on Stack Overflow, I discovered that I needed to declare a constructor like this: constructor(props) { super(props); ...

When attempting to redirect to a different page using setTimeout, the loading process appears to continue indefinitely

Currently, I am utilizing the following script: setTimeout(function(){ window.location.href = '/MyPage'; }, 5000); While this script successfully redirects me to /MyPage, it continuously reloads every 5 seconds. Is there a way to r ...

What is the best way to set up multiple routes for a single component in React

I am currently using Vue 2 in my project and have set up the following routes: const routes = [ { path: "/suites", component: Home, }, { path: "*", component: LandingPage, }, ]; Now, I need to include an additi ...

Resolving parent routes in Angular 2

I am encountering an issue with my code. The 'new' route is a child route for the 'users' route. The 'users' route has a resolver, and everything works fine up to this point. However, after successfully creating a new user, ...

The Chevron icon is not pointing downwards even though it has already gone upwards

I want to toggle a chevron icon, but nothing seems to be happening. $("span:last").removeClass("glyphicon-chevron-down").addClass("glyphicon-chevron-up"); When I add this code below the slideToggle function without an if-else section, the icon changes to ...

Implementing a different background image for every menu item when hovering over its parent

I am trying to figure out how to achieve this. My menu is placed in a container that is 500px high, with a background image. I would like the background image to change when hovering over a parent menu item. I believed I could do this using something like: ...

Combine items in a list to calculate the sum

I'm encountering a challenge with my current project. My task involves developing a picking app that utilizes a barcode scanner. The app features a multi-step form that displays one product at a time, allowing the user to pick the item or skip it if ...

Ajax is able to fetch the URL without any issues, but the page is not being updated as expected. Instead,

I am currently working on implementing next/prev buttons using JavaScript, and have utilized a DynamicPage script for testing purposes. The only modification I made was to the beginning of the URL variable in pagenumber.js, although it essentially delivers ...

What are some methods for utilizing jQuery or Javascript to dynamically modify CSS styles depending on the current URL?

I'm working on integrating a separate navigation area file with my content using PHP includes. I have this idea where I want the links in the navigation area to change color depending on the active page (current URL). Essentially, I need jQuery or Jav ...

AngularJS - Oops! Looks like we encountered an error: [$injector:modulerr]

I have a client-server application and I am facing an issue with this error message: "Uncaught Error: [$injector:modulerr]". Despite searching for solutions, none of them seem to be fixing the problem. Here is my client-side code: angular.module('m ...

I encountered an issue where the IDs did not match while using an array to update the MYSQL database

Currently, I am facing an issue while looping through an array in node JS to update a MYSQL database. The problem arises because the array starts at 0, whereas my auto-incrementing database starts at 1. This misalignment offsets the entire database by on ...

Recharge the Div

Looking for a solution to refresh the content within a specific div, I have implemented the following code: <script> $(function() { $("#refresh").click(function() { $("#new").load("/new.php") }) }) </script> The issue I am facing is ...

"Encountering an unexpected token issue when using Babel with decorators

Attempting to utilize decorators on classes in React with babelify. Despite having the 'es7.decorators' option enabled in Babel, encountering an 'unexpected token' error when using the '@' symbol. Looking for some insights or ...

Is there a quicker method to access an object's ID?

Within my array of objects, the structure is as follows: var locations = [ [{id: 1, lat: 51.52376322544537, lng: 5.13785702262885, content: 'Title A'}], [{id: 2, lat: 51.52358632767757, lng: 5.137921395645208, content: 'Title B'}], [{i ...

Tips for clear a single input tag in a form using only html5

After attempting the example below, my goal is to achieve the functionality where pressing the reset button will only reset the field in the current line. Is this achievable using only HTML5 without jQuery/JavaScript? Any suggestions or ideas are welcome ...

Preventing audio from being muted using JavaScript requires the removal of audio tags through a MutationObserver

I attempted to utilize the script below to eliminate all audio from a specific website: // ==UserScript== // @name addicto // @namespace nms // @include http://* // @include https://* // @version 1 // @grant none // ==/UserScrip ...

Using AngularJS to bind models to a multidimensional array

As I am new to angular js, please bear with me. In my view, I have a grid of text input boxes that I would like to map to a 2D array in my controller or something similar in java script. The code in my view is as follows: <div ng-repeat="row in [1,2,3, ...

The page source is not retrieved correctly by the driver

I'm facing an issue while trying to load a web page. My goal is to scroll to the very bottom of this page (which has infinite scroll) and retrieve the entire page source code. Even though scrolling and loading appear to be functioning correctly, when ...

Delineate parameters and the various endpoints of an API

Having multiple express API endpoints serving different purposes, I am facing an issue where a single endpoint is returning results for all requests. For instance, the "api/:id" endpoint should return the id, while the "api/:id?region=east" endpoint should ...

Is it better to use one large CSS file for Angular 2 or opt for separate files per component

When working with Angular 2, the choice of how to style your application is an important decision. Should you create one large minified .css file using a task runner like Gulp, or use Angular 2's styleUrls: ['myfile.css'] for each component? ...