getAttribute(’style’), setAttribute(’style’) & IE Don’t Mix

Apr

06

I was recently working on an idea I had to be able to increase and decrease the size of a div using a little JavaScript. I figured the best way to do this was by using DOM objects and methods. The specific nodes I was going to use were getAttribute (to grab the height of the div) and setAttribute (to set the new height of the div). Guess what? It worked great in Firefox, while returning an error in IE. Surprise, surprise!

getAttribute('style') - The Problem

Using document.getElementById('[id_of_element]').ge tAttribute('style') returns a string in Firefox (ex. "height: 200px"), yet in IE it merely returns an object. Which means additional code to get this into a string.

getAttribute('style') - The Solution

var el = document.getElementById('[id_of_element]');
var styleattribute = el.getAttribute('style');
if (typeof styleattribute == 'string') { // what Firefox returns
    ...
} else if (typeof styleattribute == 'object') { // what IE returns
    styleattribute = styleattribute .cssText;
}

One thing to note here, is that styleattribute.cssText returns ALL CAPS. Meaning: if the element contains style="height:200px;", styleattribute.cssText will return HEIGHT: 200px.

setAttribute('style') - The Problem

This just flat out doesn't work in IE. See entry at quirksmode.org.

setAttribute('style') - The Solution

document.getElementById('[id_of_element]').style.he ight = 250;

So, there you have it. Yet another reason to hate IE. At least there's a solution to the problem, albeit a rather annoying one.

1 CommentComments

  1. Gravatar must be down Tyler Waters

    IE can suck my nuts. I ran into this bug (amung like 3 or 4 other non-compliancy issues) while writing a cross-browser XML/XSLT processor.

    You may want to try this:
    object.style.cssText = styleText;

    where
    - object = document.getElementById(’[id_of_element]‘)
    - styleText = “height:250px;”

    Works in both IE, Mozilla & Opera
    — I’ve been unable to test other browsers.

    I have a sneaking suspicion that cssText is one of those evil proprietary properties like innerHTML that spreads like terminal cancer accross much of the web… As such, every time I want to set the style of a dom element, I call a function:

    function setStyle( object, styleText ) {
    object.style.cssText += styleText;
    }

    which can eventually be rewritten in the bright & brilliant future of FULL W3C compliancy for ALL browsers (dreaming), or modified to include further cross-browser support.

Leave a Comment