Site Navigation

Saturday, October 27, 2007

bug 245 - setAttribute "style" does not work in IE

Issue: #245
Affects: IE6, IE7

As discussed in bug 242, IE does not allow using the DOM Method .setAttribute( name, value ); for many attributes. Some just don't work, other throw errors. For the style attribute IE just ignores the request.

Example:

<script type="text/javascript">
var myObj = docuement.getElementById('myDiv');
myObj.setAttribute('style', 'border:1px dashed #663399;font-weight:bold;');
</script>


You can access each individual style property and set them seperately using DOM 0 techniques (Basically the IE4 way), or you can use the workaround listed below.


Known Workarounds: One. Set the style property's .cssText value when dealing with IE.

Example Workaround Code:

<script type="text/javascript">
var myObj = docuement.getElementById('myDiv');
//use browser sniffing to determine if IE or Opera (ugly, but required)
var isOpera, isIE = false;
if(typeof(window.opera) != 'undefined'){isOpera = true;}
if(!isOpera && navigator.userAgent.indexOf('Internet Explorer')){isIE = true);

var styleData = 'border:1px dashed #663399;font-weight:bold;';
if(!isIE){
//use the correct DOM Method
myObj.setAttribute('style', styleData);
} else {
//use the .cssText hack
myObj.style.setAttribute('cssText', styleData);
}
</script>



Related Issues: bug 242.