Defining a class with a specific style dynamically in jQuery

Is it possible to dynamically define a class with specific style attributes using jQuery, and not set the style of all elements with this class?

I could set the class attributes at the end of the script after all the elements have been created, but is this the best way to do this? If I define a class style with $('.class').css('property','value'); at the beginning of the script, nothing will happen because the elements with the .class class have not yet been created, right?

+4
source share
3 answers

The right way to do this is to use CSS. If you want elements with class "foo" to have a bunch of properties, then put these properties in a CSS file and link them to the corresponding selector:

 .yourClass { font-weight: bold; color: green; } 

If you need to do this dynamically, you can write CSS blocks using Javascript. Put the <style> element on your page and give it the value "id":

 <style id='dynamicStyle'></style> 

Then you can install it using jQuery:

 $('#dynamicStyle').text(".yourClass { font-weight: bold; }"); 
+6
source

If I understand you, you want to add style to certain elements.

You do not need to use .css(a,b) for this. The jQuery function has an addClass("className"); function addClass("className"); which will add a class to any element you want.

 $('.originalClass').addClass('addedClass'); 

It does not overwrite the original.

Is that what you wanted?


EDIT:

Or are you saying you want to change your stylesheet in javascript?

If this is the case, there are javascript rules for changing style sheet properties.

If you (for some reason) cannot change the stylesheet, perhaps you can just save your styles in the object and apply this.

 var stylesToAdd = { background:"orange", border:"1px solid blue" } 

And use .css() to apply them.

 $('#myElement').css(stylesToAdd); 
+3
source

Not sure what you think about it, but yes - you should call the script after creating the elements. If you do not want to have a script at the end of your document, wrap it in

 $(document).ready(function() { ... }); 

or alternatively abbreviated

 $(function() { ... }); 

Thus, it starts after loading all the HTML.

0
source

Source: https://habr.com/ru/post/1307936/


All Articles