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"
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"
Share Improve this question asked May 15, 2014 at 2:34 Franco AguileraFranco Aguilera 6701 gold badge8 silver badges26 bronze badges 4 |4 Answers
Reset to default 15Code 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/
This seems to work well if you want to generate one or more iframes on loading:
var dir,name,ele,style,k,v;
dir = ...
name = ...
ele = $(document.createElement("iframe"));
$("#layout",parent.document).append(ele);
ele.attr({
src: dir +"/" +name +".html",
id: dir +name
});
style = nset[dir].monitor[name].css;
$.each(style,function(k,v){
ele.css(k,v)
});
ele.load(function(){
//next iframe or start function ... can use loaded frames
});
with relevant part of nset like this:
"lert": {
"css":{
"left": 100 ,
"top": 0 ,
"width": 320 ,
"height": 480 ,
"display": "none",
"overflow": "hidden",
"backgroundColor":"white"
}
}
You should write:
for (var key in style) {
el.style[key] = style[key]
}
Example Fiddle of what you are trying to implement:
for(var key in s) {
el.style[key] = s[key]
}
some_id
as that error looks as thoughel
is null i.e. there is nothing on the page calledsome_id
. – OJay Commented May 15, 2014 at 2:37el.style.key == 'red'
what I think you are trying to do isel.style[key] = style[key]
– Ballbin Commented May 15, 2014 at 2:47