Changing CSS class property values ​​on the fly using JavaScript / jQuery

I was faced with a unique situation, which so far has not been able to find a solution for: dynamically assigning a value to the CSS style. I know how to use jQuery to assign width, height, etc. For an element, but what I'm trying to do is actually change the value defined in the stylesheet so that a dynamically created value can be assigned to multiple elements.

What I am creating is a slide show of images that occupy the full viewport, recounting the size, height and properties of the image when resizing so that the image is always centered, prefers width in height, except when the viewing area is higher than wide (resizing does not reload the page, just runs a function to resize the image).

I successfully managed to get it to work with one image, and now I'm trying to determine the best way to assign these property values ​​to all images in a slide show without having to specify these three things individually for each image,

My question is:

Is it possible to modify property values ​​in a class on the fly? I am sure that there is an answer, I probably just do not use the correct terminology in my searches. Hope I described the problem well. TIA.

+49
javascript jquery css properties dynamic
Aug 19 2018-11-18T00:
source share
14 answers

Unlike some of the answers here, editing the stylesheet itself using Javascript is not only possible, but also better performance. Just executing $('.myclass').css('color: red') completes the loop of each element matching the selector, and individually adjusts the style attribute. This is really inefficient, and if you have hundreds of items, this will cause problems.

Changing classes by elements is a better idea, but you still suffer from the same problem that you change an attribute to N elements, which can be a large number. A better solution would be to change the class on one parent or a small number of parents, and then on targets using "Cascade" in css. This works in most situations, but not for everyone.

Sometimes you need to change the CSS of many objects to something dynamic, or there is no good way to do this by typing a small number of parents. Changing the stylesheet itself or adding a little new to override the existing css is an extremely effective way to change the display of elements. You only interact with the DOM in one place, and the browser can effectively implement these changes.

jss is one library that makes it easy to directly edit a stylesheet from javascript.

+26
Aug 19 '11 at 18:20
source share

Demo , IE Demo

You can use the following function:

 function setStyle(cssText) { var sheet = document.createElement('style'); sheet.type = 'text/css'; /* Optional */ window.customSheet = sheet; (document.head || document.getElementsByTagName('head')[0]).appendChild(sheet); return (setStyle = function(cssText, node) { if(!node || node.parentNode !== sheet) return sheet.appendChild(document.createTextNode(cssText)); node.nodeValue = cssText; return node; })(cssText); }; 

Functions

  • The function is written in vanilla-js, so it has better performance than jQuery alternatives.
  • One style sheet is created after the first call to setStyle , so if you do not call it, it will not create a style sheet.
  • The same stylesheet is reused for the next setStyle calls setStyle
  • The function returns a link to the node associated with the CSS link you added. If you call the function again with this node as the second argument, it will replace the old CSS with the new one.

Example

 var myCSS = setStyle('*{ color:red; }'); setStyle('*{ color:blue; }', myCSS); // Replaces the previous CSS with this one 

Browser support

At least it works on IE9, FF3, Chrome 1, Safari 4, Opera 10.5.

There is also a version of IE that works both in modern browsers and in older versions of IE! (Works on IE8 and IE7, but may cause IE6 to crash).

+21
Oct 27 '13 at 1:31 on
source share

Good question. Many of the answers here had a solution directly contrary to what you asked.

"I know how to use jQuery to assign width, height, etc. to an element, but what I'm trying to do actually changes the value defined in the stylesheet so that a dynamically created value can be assigned to multiple elements.
"

jQuery .css inline style elements: it doesn't change the rules of physical CSS! If you want to do this, I would suggest using a vanilla JavaScript solution:

 document.styleSheets[0].cssRules[0].cssText = "\ #myID { myRule: myValue; myOtherRule: myOtherValue; }"; 

This way you set the CSS rule for CSS styles, rather than adding an inline style.

Hope this helps!

+18
Oct 27 '13 at 1:38
source share

Like @benvie, it’s more efficient to change the stylesheet rather than using jQuery.css (which will go through all the elements in the set). It is also important not to add a new style to the head every time the function is called, because this will create a memory leak and thousands of CSS rules that must be individually applied by the browser. I would do something like this:

 //Add the stylesheet once and store a cached jQuery object var $style = $("<style type='text/css'>").appendTo('head'); function onResize() { var css = "\ .someClass {\ left: "+leftVal+";\ width: "+widthVal+";\ height: "+heightVal+";\ }"; $style.html(css); } 

This solution will change your styles by changing the DOM only once to resize. Please note that for efficient js minification and compression, you probably don't want to print css nicely, but I did this for clarity.

+8
Oct 26 '13 at 21:50
source share

Using jquery add style override to <head> :

 $('<style>.someClass {color: red;} input::-webkit-outer-spin-button: {display: none;}</style>') .appendTo('head'); 
+4
Feb 04 '13 at 22:53
source share

I have a solution for changing a value in a specific CSS class. But this only works if you keep your css in the tag. If you just keep a link to your css from external ex files.

 <style src='script.js'></style> 

this solution will not work.

If your css looks like this:

 <style id='style'> .foo { height:50px; } </style> 

You can change the tag value using JS / jQuery.

I wrote a function, maybe its not the best, but it works. You can improve it if you want.

 function replaceClassProp(cl,prop,val){ if(!cl || !prop || !val){console.error('Wrong function arguments');return false;} // Select style tag value var tag = '#style'; var style = $(tag).text(); var str = style; // Find the class you want to change var n = str.indexOf('.'+cl); str = str.substr(n,str.length); n = str.indexOf('}'); str = str.substr(0,n+1); var before = str; // Find specific property n = str.indexOf(prop); str = str.substr(n,str.length); n = str.indexOf(';'); str = str.substr(0,n+1); // Replace the property with values you selected var after = before.replace(str,prop+':'+val+';'); style=style.replace(before,after); // Submit changes $(tag).text(style); } 

Then just change the tag variable to your style tag id and execute exegute:

 replaceClassProp('foo','height','50px'); 

The difference between this and $ ('. Foo'). css ('height', '50px'); is that when you do this using the css jQuery method, all elements that have the .foo class will have a visible style = 'height: 50px' in the DOM. If you do it your way, the elements are untouched, and the only thing you will see is class = 'foo'

<strong> Benefits

  • Clear DOM
  • You can change the desired property without replacing the whole style.

disadvantages

  • Inner CSS Only
  • You must find the specific style tag you want to change.

Hope this helps.

+4
Apr 17 '14 at 21:20
source share

You cannot modify CSS class members on the fly. However, you can enter a new <style> on the page with the new css class implementation, and then disable the class. Example:

 Sample.css .someClass { border: 1px solid black; font-size: 20px; } 

You want to completely change this class, so you create a new style element:

 <style> .someClassReplacement { border: 1px solid white; font-size: 14px; } </style> 

Then you do a simple replacement through jQuery:

 $('.someClass').removeClass('someClass').addClass('someClassReplacement'); 
+3
Aug 19 '11 at 17:57
source share

Why not just use the .class selector to change the properties of each object in this class?

t

$('.myclass').css('color: red;');

+2
Aug 19 '11 at 17:56
source share

You really need to rethink your approach to this problem. Using a well-designed selector and joining a class can be a more eloquent solution for this approach. As far as I know, you cannot change the external CSS.

+1
Aug 19 '11 at 17:55
source share

YUI 2 and 3 has a module stylesheet that allows you to do just that (edit style sheets on the fly using javascript). http://yuilibrary.com/yui/docs/stylesheet/ . Therefore, I think it is possible. This is not the same as $ (". Some"). Css ({...}), but actually modify / add / remove the style definition from the stylesheet, just like the user asked.

+1
Aug 19 '13 at 14:11
source share

Well .. had the same problem and fixed it, but the solution may not be for everyone.

If you know the style sheet indexes and rules that you want to delete, try something like document.styleSheets[1].deleteRule(0); .

From the very beginning I had a main.css file (index 0). Then I created a new js_edit.css file (index 1), in which there was only one rule with properties that I wanted to delete when the page finished loading (after a bunch of other JS functions too).

Now, since js_edit.css is loaded after main.css , you can simply insert / remove rules in js_edit.css as you like and they will override those in main.css .

 var x = document.styleSheets[1]; x.insertRule("p { font-size: 2rem; }", x.cssRules.length); 

x.cssRules.length returns the number of rules in the second stylesheet (index 1), inserting a new rule at the end.

I'm sure you can use a bunch of for-loops to find the rule / property you want to change and then rewrite the whole rule on one sheet, but I found this method easier for my needs.

http://www.quirksmode.org/dom/w3c_css.html helped me a lot.

+1
Dec 01 '15 at 17:26
source share

It may be late for discussion, but I needed something like what they are talking about here, but I didn’t find anything that really did what I wanted, and did it easily. I needed to hide and show a lot of elements without visiting each element separately in order to somehow update them, which changed the display style to hidden and hidden. So I came up with the following:

 <style> /* The bulk of the css rules should go here or in an external css file */ /* None of these rules will be changed, but may be overridden */ .aclass { display: inline-block; width: 50px; height: 30px; } </style> <style id="style"> /* Only the rules to be changed should go in this style */ .bclass { display: inline-block; } </style> <script> // // This is a helper function that returns the named style as an object. // This could also be done in other ways. // function setStyle() { return document.getElementById( 'style' ); } </script> <div id="d1" class="aclass" style="background-color: green;"> Hi </div> <!-- The element to be shown and hidden --> <div id="d2" class="aclass bclass" style="background-color: yellow;"> there </div> <div id="d3" class="aclass" style="background-color: lightblue;"> sailor </div> <hr /> <!-- These buttons demonstrate hiding and showing the d3 dive element --> <button onclick="setStyle().innerHTML = '.bclass { display: none; }';"> Hide </button>&nbsp;&nbsp; <button onclick="setStyle().innerHTML = '.bclass { display: inline-block; }';"> Show </button> 

By switching the bclass rule to the inline and named style sheet that appears after any other relevant style sheets, in this case with the aclass rule, I could only update the css rule to display in one place and override its aclass rule, which also has its own display rule .

The beauty of this technique is that it is so simple, effectively a single line that does the actual work, it does not require any libraries, such as jQuery or plug-ins, and the real work of updating all the places where this change is applied is done using css browser core functionality, not JavaScript. In addition, it works in IE 9 and above, Chrome, Safari, Opera, and all other browsers that MicroSoft Edge can emulate for desktop computers and tablets / phones.

0
Aug 22 '16 at 10:25
source share
 function changeStyle(findSelector, newRules) { // Change original css style declaration. for ( s in document.styleSheets ) { var CssRulesStyle = document.styleSheets[s].cssRules; for ( x in CssRulesStyle ) { if ( CssRulesStyle[x].selectorText == findSelector) { for ( cssprop in newRules ) { CssRulesStyle[x].style[cssprop] = newRules[cssprop]; } return true; } } } return false; } changeStyle('#exact .myStyle .declaration', {'width':'200px', 'height':'400px', 'color':'#F00'}); 
0
Jul 22 '17 at 21:19
source share

This solution modifies Cycne to use ES6 syntax and exit the loop earlier for external stylesheets. This solution does not modify external style sheets

 function changeStyle(findSelector, newDeclarations) { // Change original css style declaration. document.styleSheets.forEach((sheet) => { if (sheet.href) return; const cssRulesList = sheet.cssRules; cssRulesList.forEach((styleRule) => { if (styleRule.selectorText === findSelector) { Object.keys(newDeclarations).forEach((cssProp) => { styleRule.style[cssProp] = newDeclarations[cssProp]; }); } }); }); } const styleDeclarations = { 'width': '200px', 'height': '400px', 'color': '#F00' }; changeStyle('.paintBox', styleDeclarations); 

You must also have at least one style tag in the HTML header section, for example

 <style> .paintBox {background-color: white;}</style> 
0
Dec 12 '17 at 11:54 on
source share



All Articles