Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
134
rated 0 times [  138] [ 4]  / answers: 1 / hits: 85747  / 8 Years ago, thu, february 25, 2016, 12:00:00

What is a good way to apply styling dynamically (i.e. the value of styles are created at runtime) to HTML elements with JavaScript?



I'm looking for a way to package a JavaScript widget (JS, CSS and markup) in a single component (basically, an object). The idea would be for the component to encapsulate styling (so users have a nice API to modify it instead of a more tightly coupled approach of modifying the CSS directly and having changes applied indirectly). The problem is that a single API call might imply changes to several styling elements.



The way I would do it is to construct the CSS and set thestyle atrribute to the proper elements (most likely using the ID to avoid applying changes to other areas of the markup). Is this a good solution? Is there a better way to do it?


More From » css

 Answers
39

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.


[#63162] Wednesday, February 24, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
kaitlynd

Total Points: 470
Total Questions: 108
Total Answers: 120

Location: Faroe Islands
Member since Thu, Apr 8, 2021
3 Years ago
;