Skip to content Skip to sidebar Skip to footer

How To Dynamically Change A Class Css Styling?

Goal In my program I want to do both things with jquery/javascript: Change styling of css classes dynamically Add/remove classes to elements Problem To do the first thing I use $

Solution 1:

A more shorten format:

$("<style/>", {text: ".redclass {color: darkRed;}"}).appendTo('head');

The snippet:

$("<style/>", {text: ".redclass {color: darkRed;}"}).appendTo('head');


$("p").addClass("redclass");

$("span").addClass("redclass");
<scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><p>I want to be red! And I am.</p><span>I want to be red too but I'm not :'(</span>

Solution 2:

While other (working) answers have been supplied, they don't actually answer your question - namely, they don't change the specified css class, but instead override it by adding another rule later in the document.

They achieve this, basically:

Before

.someClass
{
  color: red;
}

After

.someClass
{
  color: red;
}

.someClass
{
  color: white;
}

When in many cases, a better option would see the color attribute of the existing rule altered.

Well, as it turns out - the browser maintains a collection of style-sheets, style-sheet rules and attributes of said rules. We may prefer instead, to find the existing rule and alter it. (We would certainly prefer a method that performed error checking over the one I present!)

The first console msg comes from the 1 instance of a #coords rule. The next three come from the 3 instances of the .that rule

functionbyId(id){returndocument.getElementById(id)}

window.addEventListener('load', onDocLoaded, false);

functiononDocLoaded(evt)
{
	byId('goBtn').addEventListener('click', onGoBtnClicked, false);
}

functiononGoBtnClicked(evt)
{
	alterExistingCSSRuleAttrib('#coords', 'background-color', 'blue');
	alterExistingCSSRuleAttrib('.that', 'color', 'red');
}

// useful for HtmlCollection, NodeList, String types (array-like types)functionforEach(array, callback, scope){for (var i=0,n=array.length; i<n; i++)callback.call(scope, array[i], i, array);} // passes back stuff we needfunctionalterExistingCSSRuleAttrib(selectorText, tgtAttribName, newValue)
{
	var styleSheets = document.styleSheets;
	forEach(styleSheets, styleSheetFunc);

	functionstyleSheetFunc(CSSStyleSheet)
	{
		forEach(CSSStyleSheet.cssRules, cssRuleFunc);
	}

	functioncssRuleFunc(rule)
	{
		if (selectorText.indexOf(rule.selectorText) != -1)
		forEach(rule.style, cssRuleAttributeFunc);

		functioncssRuleAttributeFunc(attribName)
		{
			if (attribName == tgtAttribName)
            {
				rule.style[attribName] = newValue;
                console.log('attribute replaced');
            }
		}
	}
}
#coords
{
    font-size: 0.75em;
	width: 10em;
	background-color: red;
}
.that
{
	color: blue;
}
<style>.that{color: green;font-size: 3em;font-weight: bold;}</style><buttonid='goBtn'>Change css rules</button><divid='coords'class='that'>Test div</div><style>.that{color: blue;font-size: 2em;font-weight: bold;}</style>

Solution 3:

@synthet1c has described the problem. My solution is:

$("head").append('<style></style>');
var element = $("head").children(':last');
element.html('.redclass{color: darkred;}');

Solution 4:

What you are having issue with is that when you use the jQuery selector $('.redclass').css('color', 'darkRed') you are getting all the elements that currently have that class and using javascript to loop over the collection and set the style property.

You then set the class on the span after. Which was not included in the collection at the time of setting the color

You should set the class in your css file so it is distributed to all elements that have that class

console.log($('.redclass').length)
$("p").addClass("redclass");
console.log($('.redclass').length)
// $(".redclass").css("color", "darkRed");
$("span").addClass("redclass");
console.log($('.redclass').length)
.redclass {
  color: darkRed;
}
<scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><p>I want to be red! And I am.</p><span>I want to be red too but I'm not :'(</span>

Post a Comment for "How To Dynamically Change A Class Css Styling?"