Changes css styles with 'document.getElementById (o) .style [p] = v' valid?

We hope to trim some fats from our user library that we use in our products.

One of the most commonly used actions is to change the styles of objects.

Usually we do this through:

document.getElementById('object').style.property='value'; 

I just tested the following in the chromes console and it worked:

 function objStyle(o,p,v){ document.getElementById(o).style[p]=v; } objStyle('object','property','value'); 

Is this a valid way to do something?

Any pitfalls you can think of when using this way of doing business? Crossbrowser compatible?

+4
source share
2 answers

Yes, that’s absolutely true. The property you are accessing .name can also be accessed by ['name'] .

This works for any property in any object, for example:

 window['alert']('Hello world.'); document['getElementById']('object')['style']['color'] = '#fff'; 
+5
source

Your code is ok.

One thing I would consider is whether you want to continue calling document.getElementById() (inside a function) if there is a situation where you need to make several changes to the same element. What I'm going to suggest is redundant to show you more parameters, but think that you can pass the Id to your function or pass a link to an element directly or have a function that takes a string or the element refers to it and indicates its type type:

 function objStyleById(oId,p,v){ document.getElementById(oId).style[p]=v; } function objStyle(o,p,v) { o.style[p] = v; } function objStyleAuto(o,p,v) { if (typeof o === "string") o = document.getElementById("o"); // else not a string so assume o is element reference o.style[p] = v; } objStyleById('object','property','value'); var myEl = document.getElementById("someElement"); objStyle(myEl,"prop","val"); objStyle(myEl,"prop2","val"); // some other non-style operation on myEl, eg, myEl.className = "something"; myEl.innerHTML = "something"; objStyle(myEl.parentNode,"prop","value"); objStyleAuto('object','property','value'); objStyleAuto(myEl,'property','value'); 
+1
source

All Articles