Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set css properties with a json

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"

like image 436
flaalf Avatar asked May 15 '14 02:05

flaalf


People also ask

Can we add CSS in JSON file?

There are various methods to convert the JSON data into usable CSS custom properties. One method I've used successfully is using PostCSS and the PostCSS-Import-JSON plugin. The plugin imports the JSON file and converts the data into CSS custom properties. Let's look at a basic use-case example.

How do I display formatted JSON data in HTML?

Use the JSON. stringify function to Display formatted JSON in HTML. If you have unformatted JSON It will output it in a formatted way. Or Use <pre> tag for showing code itself in HTML page and with JSON.


1 Answers

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/

like image 111
ujeenator Avatar answered Sep 30 '22 14:09

ujeenator