How to dynamically create CSS class in JavaScript and apply?
Here is an option:
var style = document.createElement('style');
style.type = 'text/css';
style.innerHTML = '.cssClass { color: #F00; }';
document.getElementsByTagName('head')[0].appendChild(style);
document.getElementById('someElementId').className = 'cssClass';
How to dynamically create CSS class in IE8
According to MSDN:
The innerHTML property is read-only on the col, colGroup, frameSet, html, head, style, table, tBody, tFoot, tHead, title, and tr objects.
So, try to use innerText
to write these class.
Updated:
You can use:
style.styleSheet.cssText = '.cssClass { color: #F00; }';
Or do a test:
if (style.styleSheet){
style.styleSheet.cssText = '.cssClass { color: #F00; }';
} else {
style.appendChild(document.createTextNode('.cssClass { color: #F00; }'));
}
Hope, it now runs! :)
How to dynamically change CSS class of an HTML tag?
You can add a CSS class based on id
dynamically using classList
API as follows:
document.getElementById('idOfElement').classList.add('newClassName');
Or the old way:
document.getElementById('idOfElement').className = 'newClassName';
// += to keep existing classes
Alternatively you can use other DOM query methods shown below to find elements. The last three return a collection so you'll have to iterate over it and apply the class to each element in the collection (similar to the example given below each).
querySelector
querySelectorAll
elements.forEach(element => element.classList.add('newClassName'));
getElementsByClassName
Array.from(elements).forEach(element => element.classList.add('newName'));
getElementsByTagName
Array.from(elements).forEach(element => element.classList.add('newName'));
In your case
var element = document.getElementById('div1');
if(boolVal)
element.className= 'blueClass'; // += ' blueClass'; to keep existing classes
else
element.className= 'redClass';
Creating a css class with a Javascript object or var
Lots of ways to dynamically alter css styling after page load.
If you want to make a change that is applied as if it was a normal css script you can add a style tag to the header via javascript.
eg.
var color = "blue" ; // from your input
var element = document.createElement("style");
element.id = "myStyleId" ; // so you can get and alter/replace/remove later
element.innerHTML = ".myClass {color:" + color + ";}" ; // css rule
var header = document.getElementsByTagName("HEAD")[0] ;
header.appendChild(element) ;
Apply a Css Class in Javascript
As the previous answer (from abhishek sahu) suggest you can use:
target.classList.add('yourClass');
But, i guesss it's your case, if you want to add and remove the class on every click (so for example you want to click once and add the class and when you click again remove it from the same element) you can use:
target.classList.toggle('yourClass');
The toggle
method add a class on an alement if it does't have it already, if so it removes that class
Apply CSS dynamically with JavaScript
Using Jquery
Use the css() function to apply style to existing elements where you pass an object containing styles :
var styles = {
backgroundColor : "#ddd",
fontWeight: ""
};
$("#myId").css(styles);
You can also apply one style at the time with :
$("#myId").css("border-color", "#FFFFFF");
Vanilla JS :
var myDiv = document.getElementById("#myId");
myDiv.setAttribute("style", "border-color:#FFFFFF;");
With Css :
You can also use a separate css file containing the different styles needed inside classes, and depending on the context you add or remove those classes to your elements.
in your css file you can have classes like
.myClass {
background-color: red;
}
.myOtherClass {
background-color: blue;
}
Again using jquery, to add or remove a class to an element, you can use
$("#myDiv").addClass('myClass');
or
$("#myDiv").removeClass('myClass');
Again, you can also do the same with vanilla JS:
document.getElementById("#myId").classList.add('myClass')
or
document.getElementById("#myId").classList.remove('myClass')
I think this is a cleaner way as it separates your style from your logic. But if the values of your css depends from what is returned by the server, this solution might be difficult to apply.
How to apply CSS module with a dynamically created className
If you are using css module in react, you don't need to use article.activeSlide
. As it is just one module related css. Use activeSlide
in css file and style[position]
where you want to use it
Related Topics
How to Get the Onclick Calling Object
Angularjs to Output Plain Text Instead of Html
Print ≪Div Id="Printarea"≫≪/Div≫ Only
How to Get a Style Attribute from a CSS Class by JavaScript/Jquery
"Uncaught Typeerror: A.Indexof Is Not a Function" Error When Opening New Foundation Project
Use ≪Canvas≫ as a CSS Background
Er_Not_Supported_Auth_Mode - MySQL Server
Is JavaScript a Pass-By-Reference or Pass-By-Value Language
How to Compare Arrays in JavaScript
How to Find Out Which Dom Element Has the Focus
How to Detect Which One of the Defined Font Was Used in a Web Page
Get Json Data from External Url and Display It in a Div as Plain Text
How to Save a Base64 Image to User'S Disk Using JavaScript
Setting CSS Pseudo-Class Rules from JavaScript
React Js Conditionally Applying Class Attributes
List Every Font a User'S Browser Can Display