views:

251

answers:

1

I'm working on adding content to a web-page with javascript. The problem is that the CSS in IE (7) doesn't seem apply to the dynamically added content.

Here's an example document..

<html>
<head>
    <style type="text/css">
    p.foo { color: #FF4400 ; background-color: #000000 }
    p.bar { color: #FF0000 ; background-color: #000000 }
    </style>
    <script type="text/javascript">
        function add() {
            var node = document.createElement("p");
            node.setAttribute("class", "bar");
            node.appendChild(document.createTextNode("New Content"));
            document.body.appendChild(node);
        };
    </script>
</head>
<body onload="add()">
        <p class="bar">bar</p>
        <p class="foo">foo</p>
</body>
</html>

In FF, the newly added 'New Content' paragraph has the style applied to it, but in IE, it doesn't. This seems like something obvious enough that it ought to be easily searchable-for, but some obvious queries gave me nothing.

So what's the trick?

+5  A: 

Why not use a framework, such as jQuery, MooTools, extJs, Dojo, Prototype, etc., that has already solved all of these problems?

But if you insist on doing it yourself, try using:

    function add() {
        var node = document.createElement("p");
        node.className = 'bar'; // <- use in leu of setAttribute()
        node.appendChild(document.createTextNode("New Content"));
        document.body.appendChild(node);
    };
tvanfosson
Could you please share the name of the framework(s) that have already solved all of these problems?
overslacked
Dan Herbert
Almost every javascript framework handles cross-browser issues like this. I use jQuery -- but you might also look at prototype/scriptaculous, mootools, extjs, etc.
tvanfosson
I think it would be helpful if the answer were edited to include the framework names.
overslacked