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"
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.
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.
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With