I want to change the style tag after generating contents. How can I add style to the style tag? I tried using:
document.getElementById('style').appendChild(styleContents);
but it did not work
The HTML DOM allows JavaScript to change the style of HTML elements.
Yes!
style. color = "red"; you can apply the style change dynamically. Below is a function that turns an element's colour to red when you pass it the element's id . You could also use setAttribute(key, value) to set a style on an element.
If you want to change the CSS styles dynamically you'll have to attach this portion of code to some event. For example, if you want to change the styles of your element when clicking on a button, then you have to first listen to the click event and attach a function containing the previous code.
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
I know this is an old question but I have been trying to figure out a way to dynamically update these as well without applying styling directly to the element.
If you give a style tag an ID and select it you can then access its CSS using sheet property.
From here you can update anything you want. By replacing the entire CSS inside the tag or updating individual classes.
document.getElementById('somestyletagid').sheet.cssRules[0].selectorText
This is your class selector.
document.getElementById('somestyletagid').sheet.cssRules[0].style
These are are all the individual css properties on that class.
You can update the background color by doing this:
document.getElementById('somestyletagid').sheet.cssRules[0].style.backgroundColor = 'red'
This is a way to access any style tags in your html. Unfortunately there is no strictly unique ID for each CSSStyleRule that I can find. Closest is the selectorText but obviously that can be repeated. Either way at least for my needs this does exactly what I need.
You can also update any included CSS files by using document.styleSheets and accessing them in generally the same way.
document.styleSheets[0].href
The href of the included css file.
document.styleSheets[0].cssRules
All the classes in the sheet.
Hope this helps someone!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With