How to Create a ≪Style≫ Tag With JavaScript

How to create a style tag with Javascript?

Try adding the style element to the head rather than the body.

This was tested in IE (7-9), Firefox, Opera and Chrome:

var css = 'h1 { background: red; }',
head = document.head || document.getElementsByTagName('head')[0],
style = document.createElement('style');

head.appendChild(style);

style.type = 'text/css';
if (style.styleSheet){
// This is required for IE8 and below.
style.styleSheet.cssText = css;
} else {
style.appendChild(document.createTextNode(css));
}

Will adding an id to a html style tag cause issues?

You don't have to get it by id again. You have it in styleEl variable, so just remove it from a DOM like this:

styleEl.remove(); // remove it from the DOM

You can do this repeatedly. Append and remove.

Trying to add style tag using javascript (innerHTML in IE8)

jQuery

Since you're already using jQuery, use:

 $('<style type="text/css">' + 
'.some_class {overflow:hidden}' +
'.some_class > div {width:100%;height:100%;}' +
'</style>').appendTo('head');

Pure JavaScript

If you don't want to use jQuery, you have to first append the <style> element, then use the style.styleSheet.cssText property (IE-only!!).

var d = document,
someThingStyles = d.createElement('style');
d.getElementsByTagName('head')[0].appendChild(someThingStyles);
someThingStyles.setAttribute('type', 'text/css');

someThingStyles.styleSheet.cssText = " \
.some_class {overflow:hidden} \
.some_class > div {width:100%;height:100%;} \
";

Replace style tag with javascript equivalent

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>

Creating the dynamic style tag with the incrementing ID

I would advice you to use some other approach (using css like other people recommend here), but if you really want to try generate the styles manually then you can generate styles string (in the example using RegExp and placeholders) and then append it to head tag:

$array = {  "sections": {    "H": {      "name": "dummy",      "html": "<div id=\"dummy\"><h1>Some Title</h1><p>This is a para</p></div>"    }  }}
var defaultStyle = "#dummy--{id} {background-color: bisque;}#dummy--{id} H1 {color: {h1-color};font-size: 20px;}#dummy--{id} p{color: green;font-size: 15px;}"
$(function() { // counter which holds the counts of click var count = -1; $('#cm').click(function(event) { $htmlData = $array["sections"]["H"]['html']; // check the count value for second click if (++count > 0) // in case of not a first click parse the html and generate a jQuery object $htmlData = $($htmlData).attr('id', function(i, v) { // update the attrubute value return v + '--' + count // get back the html content from the DOM object })[0].outerHTML //$('#content').html($htmlData); $($htmlData).appendTo('#content').hide().slideDown(); var generated = defaultStyle.replace(/{id}/gi, count).replace(/{h1-color}/gi, count % 2 ? "red":"yellow"); $("<style type='text/css'>" + generated + "</style>").appendTo("head"); });})
#dummy {  background-color: bisque;}#dummy H1 {  color: blue;  font-size: 20px;}#dummy p {  color: green;  font-size: 15px;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><button id="cm">Click me</button>
<ul id="content"> </ul>

How to dynamically change the style tag using JavaScript?

You are probably trying to add css to the style tag. This can be accomplished using:

document.getElementsByTagName('style')[0].innerHTML=""; //some css goes here

You can also use:

document.styleSheets[0].cssText = ""; //some css goes here

Serialized and deserialize HTML style tag with CSS

So it seems that this has to do with creating the style node dynamically on a new document.

The easiest reproduction is as follows:

const doc = new Document()

const style = doc.createElement('style')
style.textContent = '.a>.b { color: red; }'

console.log(style.outerHTML)

Which yields <style>.a>.b {color:red}</style>

It seems that being part of actively rendered document/or just generally being added to a document and not just created using it has some side-effect on the style node, which causes it to be serialized properly though. So now I do the following instead as a workaround, which is a bit ugly but works:

const doc = new DOMParser().parseFromString('<html><head></head><body></body></html>', 'text/html')


const style = doc.createElement('style')
style.textContent = '.a>.b { color: red; }'

doc.body.append(style)

console.log(style.outerHTML)

doc.body.removeChild(style)

Which produces an appropriately serialized <style>.a>.b { color: red; }</style>

Now this solves my problem, but I'd still really like to understand what is happening here in more detail (e.g. what is the side-effect exactly and how/when is it triggered), so would appreciate comments on that!



Related Topics



Leave a reply



Submit