Search code examples
javascriptcssinternet-explorerquirks-mode

Adding a class to an element in quirksmode


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)


Solution

  • 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')