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 a time when:
$("#myId").css("border-color", "#FFFFFF");
Vanilla JS:
var myDiv = document.getElementById("#myId"); myDiv.setAttribute("style", "border-color:#FFFFFF;");
Using Css:
You can also use a separate css file containing the different styles needed inside the classes, and depending on the context that you add or remove these classes in your elements.
in your css file you can have classes like
.myClass { background-color: red; } .myOtherClass { background-color: blue; }
Using jquery again to add or remove a class to an element, you can use
$("#myDiv").addClass('myClass');
or
$("#myDiv").removeClass('myClass');
I think this is a cleaner way as it separates your style from your logic. But if your css values depend on what the server returns, this solution can be difficult to apply.
kerwan
source share