tags:

views:

66

answers:

2

i'm using java script to dynamically create an element and populate it with content. after i appended it as a child to an existing element of the current dom tree, the browser ignores my defined CSS. Using firefox i installed the web developer toolbar and noticed that when i turn off css style sheets and turn it on again, the element is displayed properly. (pushing Strg + Shift + S twice) Internet Explorer is doing fine, but FF,Chrome are refusing to do it.

my code:

var elem = document.createElement("pre");
var node = document.createTextNode("<span class=\"green\">i should be green</span>");
elem.appendChild(node);

var el = document.getElementById('div1');
el.innerHTML = "";
el.appendChild(elem);

i tested the code in a simple test page where nothing else than 'div1' existed and it worked. but in my web application it doesnt work. strange for me because i'm doing that all the time and suddenly i encountered a case where it doesnt work.

Are there any common problems with css rendering issues after replacing content dynamically? Is there a way to force a refresh like the firefox developer toolbar is doing?

thanks,

+2  A: 

use:

var elem = document.createElement("pre");
var span = document.createElement("span");
span.setAttribute("class","green");
var node = document.createTextNode("i should be green");
span.appendChild(node);
elem.appendChild(span);

var el = document.getElementById('div1');
el.appendChild(elem);

Just use DOM methods to create the nodes you want.

Jonathan Fingland
well, my example above was a very simplified one. real truth is that i create content dynamically, append it to the dom tree and another lib is changing and inserting span-tag's to beautify my content. adding the content and inserting the span-tags happens. but the browser doesnt update the view.
ManBugra
without knowing more about the situation, all I can really say is that your code beautifying JS is not working terribly well. For my blog I use highlight.js ( http://softwaremaniacs.org/soft/highlight/en/ ) and have no such problems. mixing innerHTML and DOM methods is likely creating the problem you're having.
Jonathan Fingland
i fixed the issue. i used following line to include the css:<link title="My CSS" rel="stylesheet" type="text/css" media="all" href="my.css"/> and it didnt work. after removing the title attribute it worked.
ManBugra
A: 

Ctrl + F5 should sort it

polbek
Suggesting a page refresh rather defeats the purpose of writing scripts and styles to enable dynamic web content.
Eric Kolb