0

This is my function set css attributes like as jquery

that.getNode = function() {
    return element;   // element is HTML node
};    


that.css = function(obj) {
    var node = that.getNode(),
        attr;
    if (node && node.style) {
        for (attr in obj) {
            if (obj.hasOwnProperty(attr) && node.style.hasOwnProperty(attr)) {
                node.style[attr] = obj[attr];
            }
        }
    }
    return that;
};

Then I call, it runs on Chrome normally but can't work on IE9 or firefox

that.css({
    border: "1px solid black"
});
Toan Nguyen
  • 1,043
  • 3
  • 13
  • 24
  • there are similar questions on SO, http://stackoverflow.com/questions/524696/how-to-create-a-style-tag-with-javascript http://stackoverflow.com/questions/7527447/css-in-javascript – shweta Apr 29 '13 at 04:28

2 Answers2

2

Seems that the following returns false in some browsers:

node.style.hasOwnProperty(attr)

In these cases, the properties are being inherited from a prototype rather than owned by the Object (node.style) itself.

If you want to test that the property exists, whether owned or inherited, you can try the in operator:

attr in node.style

In context:

that.css = function(obj) {
    var node = that.getNode(),
        attr;
    if (node && node.style) {
        for (attr in obj) {
            if (obj.hasOwnProperty(attr) && attr in node.style) {
                node.style[attr] = obj[attr];
            }
        }
    }
    return that;
};
Jonathan Lonowski
  • 121,453
  • 34
  • 200
  • 199
0

Make a Cross-browser solution by hand is lot of work, I recommend using some JavaScript Framework like JQuery, it will do the hard work for you.

If you choose JQuery you have a function named .CSS and you could do this task in 1 line, for example:

You have an HTML element:

<div id="someID"> Content </div>

right? so you want to add some CSS Classes to this DIV, you only need to say to JQuery which node in the HTML DOM want to select and with the function .CSS you can set some CSS Attributes (and other things):

$("#someID").css("SOME-ATTRIbute","SOME-VALUE");

(#someID is the ID of the element, .CSS is the function)

easy eh?, Use JQuery or any other Javascript Frameworks that will help you to do a cross-browser application.

PS: sorry for my english

FxckDead
  • 408
  • 6
  • 16