Search code examples
cssdynamic-data

css for dynamic content


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?


Solution

  • 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);
        };