0

i have a object dom which have a property named changeCss which changes the css on any element: the code is as follows:

var Dom = {
 changeCss : function(element, properties){
            if(typeof (properties) === "object"){

                var properties_name = Object.keys(properties),
                     properties_value = [];

             for ( var i = 0; i < properties_name.length ; i++  ){
                 var a = properties_name[i],
                  b = properties[a];

                  properties_value[i] = b;

                  element.setAttribute("style", a+":" + b+";");

             };

            }else{
                throw 'properties of '+ element +" should be object";  
            }   
        },  
} 

so from this code you will be understand how i want to change the css of any element,and this is working perfectly. But the problem which i am facing is that if i am writing this code:

var x = document.getElementById("some_html_tag_id");
Dom.changeCss(x, {"width": "100px", "height":"80px"});  

then the style element only consist height:80px not width:100px ! how to add all these style properties?

thanks

anni

2 Answers 2

3

First of all replace

element.setAttribute 

with

element.style[a]= b;

But basically you should understand that YOU do. SetAttribute function set's new value to attribute style. So while i==0 style='width:100px;' while i==1 style= 'height:80px;'

because you just override value. If you want to keep SetAttribute function in your code. You need to concat all the values first, and then use set attribute

Sign up to request clarification or add additional context in comments.

Comments

1

In the DOM. The style attribute is not a string. It's an object. Which means you should do this instead:

element.style.setProperty(a,b);

However, older versions of IE doesn't support setProperty for style objects. So, even though the above is technically the standards compliant way of doing it, the guaranteed cross-borwser method that works is:

element.style[a] = b;

Note that for every instance where you think you need setProperty or setAttribute, the object[x] = y syntax will also work and in the case of styles is always backwards compliant (not to mention requires less typing).

2 Comments

It should work except for older versions of IE which doesn't support setAttribute for style objects.
When talking about cross-browser methods, maybe it's good to mention, that FF requires camel-cased property name when using element.style[a] = ..., other browsers accept both camel-cased and hyphen form.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.