-1

An HTML page has an inline block in the HEAD like so:

<style type="text/css">
  body {font-size: 1.2em}
</style>

This sets the body font size immediately when the page is loaded.

I want to replace this with something more dynamic but still on the client side.

How can I use JavaScript to set such a style that would be available and visible immediately that the page is rendered? Body.onload is too late. I need an equivalent to this style block, but with JavaScript.

Craig
  • 1,277
  • 2
  • 16
  • 29

2 Answers2

0

The answer was to use document.head.innerHTML += in an inline script block to add HTML representing the STYLE block and style. This is added to the DOM immediately after the SCRIPT tag that creates it. Using backticks for the HTML template containing the font size would have made it even easier, though in the end I had to support IE 11 so backticks were out.

The solution:

<script>
    var fontSize = //font size retrieved here;
    document.head.innerHTML += "<style type=\"text/css\"> \nbody { font-size: ".concat(fontSize, "em } \n</style>");
</script>
Craig
  • 1,277
  • 2
  • 16
  • 29
-1

How about this. I suppose that you can not insert CSS directly.

<p id="myCSS"></p>
<script><!--
document.getElementById("myCSS").outerHTML=[
  '<style type="text/css">'
 ,'body { font-size: 1em; line-height: 1.5em }'
 ,'<\/style>'].join('\r');
-->
</script>

Note that some CSS settings are hard to recovery to it's original one. With the css value unset you can do that, but IE does not support it. In such cases, maybe 'try and error' is the best you can do.

Jack Ting
  • 552
  • 4
  • 6