css not being applied to document.write text

hideyho picture hideyho · Jan 25, 2011 · Viewed 8.2k times · Source

I'm writing text to a page using document.write for a Chrome extension, but the associated custom CSS isn't applied:

<!DOCTYPE html>
<html>
<head>
    <title>TITLE GOES HERE</title>
     <link rel="stylesheet" href="css/popup.css" type="text/css" />
</head>

<body>
     <script type="text/javascript">
        ...
        function showFolder(folder) {
            console.debug('FOLDER: '+folder.title);
            document.write('<p>'+folder.title+'<br></p>');
        }
    </script>

</body>
</html>

The CSS is simple, just for debugging:

p {
color: red;
}

I can get it to work if I put the stylesheet link inside the function showFolder, but that can't be the proper way to do it. I'm learning jscript/CSS on the fly, so the answer is probably something remedial. Is the problem in the jscript, the CSS or both?

Answer

Zoltan Lengyel picture Zoltan Lengyel · Jan 25, 2011

Use innerHTML.

<div id="towrite"></div>

then you can write in it like this:

div=document.getElementById('towrite');
div.innerHTML = '<p>'+folder.title+'<br></p>';