Css does not apply to document.write text

I am writing text to a page using document.write for the Chrome extension, but the corresponding custom CSS is not 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> 

CSS is simple, just for debugging:

 p { color: red; } 

I can make it work if I put the stylesheet link inside the showFolder function, but this may not be the right way to do this. I learn jscript / CSS on the fly, so the answer is probably something fixed. Is the problem in jscript, CSS or both?

+5
source share
3 answers

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>'; 
+3
source

If you run document.write () before the page finishes loading (perhaps by calling your showFolder call directly from the script on the page), then the text will be written to the document, as you might expect.

However, if you call document.write after the page loads, as in the event handler, you will write a completely new page. This is usually not what you want.

Instead, follow the Zoltan tips and set the innerHTML property to an empty div.

+1
source

I am not a javascript expert ... I mainly use jQuery .. but try this, something makes sense:

 <!DOCTYPE html> 

TITLE GOES HERE

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

EDIT:

So that didn't work, but I just thought of a different solution. When do you actually call this function? Try putting it in <body onLoad="functionnamehere()">

I don't know if this works, but try it.

0
source

Source: https://habr.com/ru/post/1336903/


All Articles