Set css properties with a json

14,485

Code example:

Object.assign(document.querySelector('.my-element').style, {
    position: 'fixed',
    top: 0,
    right: 0,
    bottom: 0,
    left: 0,
    background: 'red'
})

Example on JSFiddle:

https://jsfiddle.net/b6hexafL/4/

Share:
14,485
Franco Aguilera
Author by

Franco Aguilera

Javascript enthusiast, always on the search for new problems

Updated on June 13, 2022

Comments

  • Franco Aguilera
    Franco Aguilera almost 2 years

    i've follow the w3c description for setting up the css properties of an element with javascript, but i cant figure how to do it with a json object.

    my code is this :

    var style = {
        position:'fixed',
        top:0,
        right:0,
        bottom:0,
        left:0,
        background:'red'
    }
    
    
    var el = document.getElementById( 'some_id' );
    for( var key in style ){
        el.style.key = style[key]
    }
    

    but when a run my script i get "Uncaught TypeError: Cannot read property 'style' of null"

  • Franco Aguilera
    Franco Aguilera about 10 years
    sorry guys, i not seems to work. i mean.. all i'm trying to do is to set the css properties with a for loop , iterating through an object.
  • Franco Aguilera
    Franco Aguilera about 10 years
    i think that the problem is about set up the "key" variable in el.style.key = css[key] inside the loop. because when i iterate key stand for the name of the property and css[key] stands for the value of the property ( i change style for css )
  • 雪月秋水
    雪月秋水 about 10 years
    I do it ,please check the example link and tell me your think