Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use jQuery's .css() with variable property name?

Instead of writing:

$('div').css({'backgroundColor': 'red'});

I want to write something like:

$('div').css({get_property_name(): 'red'});

where get_property_name() will return "backgroundColor", "color", "border-top-color", or any other property.

What options do I have to make it work ?

like image 673
Misha Moroshko Avatar asked Sep 20 '10 10:09

Misha Moroshko


People also ask

How do you retrieve a CSS property value of an element?

The attr() CSS function is used to retrieve the value of an attribute of the selected element and use it in the stylesheet. It can also be used on pseudo-elements, in which case the value of the attribute on the pseudo-element's originating element is returned.

How can check CSS property value in jQuery?

How can check CSS property value in jQuery? Get a CSS Property Value You can get the computed value of an element's CSS property by simply passing the property name as a parameter to the css() method. Here's the basic syntax: $(selector). css(“propertyName”);

Can we change CSS properties values using JavaScript?

CSS variables have access to the DOM, which means that you can change them with JavaScript.

How can give multiple CSS properties in jQuery?

Apply multiple CSS properties using a single JQuery method CSS( {key1:val1, key2:val2....). You can apply as many properties as you like in a single call. Here you can pass key as property and val as its value as described above.


2 Answers

The .css() method can also be called as .css(propertyName, value).

$('div').css(get_property_name(), 'red');

If you really need the dictionary representation:

var d = {};
d[get_property_name()] = 'red';
$('div').css(d);
like image 109
kennytm Avatar answered Oct 23 '22 20:10

kennytm


Just assign an object those values and pass it to .css()

var styles;
styles[get_property_name()] = 'red';
$(div).css(styles);
like image 30
Randy the Dev Avatar answered Oct 23 '22 18:10

Randy the Dev