Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: How to set style selector from var

Tags:

javascript

css

I have a problem with styles in JavaScript.

I have a object like: styles = {background:'blue',width:'1000px'}

I need write function which takes every attributes from styles object and apply it as a CSS selectors of some HTML element.

something like:

function stylize(def){
     for(var key in def){
         document.getElementById("test").style.***SELECTOR***=def[key];
     }

}

but how get style selector by value of key value?

I need pure JS solution withour jquery etc.

like image 785
ELP24 Avatar asked Jan 29 '26 15:01

ELP24


1 Answers

Just use the square bracket notation:

function stylize(def) {
    for (var key in def) {
        document.getElementById("test").style[key] = def[key];
    }
}

Note: this is just an example; not production code.

like image 80
Salman A Avatar answered Jan 31 '26 04:01

Salman A



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!