views:

55

answers:

2

I try to add a class to a td-element using javascript with the internet explorer 8 in quirks-mode. That seems to work, because I can see the added class when I view the source, but my css doens't affect it so nothing visually changes at all. I simply add a html class to change the background-color but nothing happens. It works when running in IEs normal mode, but that's not an option because I can't change the site and it's running in quirks-mode.

EDIT:

Here is a simple example:

<html>
<head>
<style>
    .style1 { background-color: #ff0000; }
    .style2 { background-color: #00ff00; }
</style>
</head>
<body>
<table id="table1">
    <tr>
        <td>some text</td>
        <td>goes on</td>
        <td>and on</td>
    </tr>
</table>
<script type="text/javascript">
    var tableElement = document.getElementById("table1");
    tableElement.setAttribute("class", "style1");
</script>
</body>
</html>

Note that it doesn't work in quirks-mode (tested with IE 8) although the class is getting added (can be viewed with IE developer tools)

+1  A: 

I came up with a system that builds a stylesheet based on whatever styles you want to add to an element and then adds it into the HTML. It seems to work on just about all the browsers I've tried including various flavours of IE. It doesn't work with classes but could easily achieve what you describe above.

Article: http://www.4pmp.com/2009/11/dynamic-css-pseudo-class-styles-with-jquery/

SlappyTheFish
That's a nice approach too, but foo.className = 'bar' is the better solution for my problem.
wroks
+2  A: 

Internet Explorer 7 and lower (and 8 when emulating 7) have a completely broken implementation of setAttribute (and getAttribute).

Effectively it works like this:

HTMLElement.prototype.setAttribute = function (property, value) {
    this[property] = value;
}

This breaks when the property name and attribute name are not the same (such as when the property name is a reserved word (like class) or used for something else (like style)).

Use foo.className = 'bar' instead of foo.setAttribute('class','bar')

David Dorward
That's it! Thank you
wroks