Search code examples
javascriptcssz-index

Why can't I set z-index through javascript with this function? (I know about camelcase)


Hi I want to change the z-index of my DOM element, so I used a function to do so. The function works for many properties but not z-index I am using Dev Tools and I can see that it is not even being set on the element and I do not know why.

Javascript:

    function setStyle(obj, propertyObj) {
        for (var property in obj) {
             if(obj.hasOwnProperty(property)){
                obj.style[property] = propertyObj[property];
            }
        }
    }
    var img = new Image();
    img.onload = function() {
       setStyle(this, {'zIndex':'-5'}) ;
    };
    img.src = 'test.jpg'

EDIT

Thanks for the good answers.

I was applying a border in the CSS code somewhere, so when I was looping through the objects properties border was being changed (but the same was not true for z-index).


Solution

  • Might as well add yet another answer...

    typeof obj.style === 'object' && Object.keys(propertyObj).forEach(function(key) {
        obj.style[key] = propertyObj[key];
    });
    

    IMO, Object.keys is superior to a for ... in loop as it is immune from Object prototype injection problems.

    This also ensures that obj has a style property to begin with.

    Update

    Because some people are in to micro-optimisation, here it is without the Array.forEach

    if (typeof obj.style === 'object') {
        var keys = Object.keys(propertyObj);
        for (var i = 0, l = keys.length; i < l; i++) {
            var key = keys[i];
            obj.style[key] = propertyObj[key];
        }
    }