Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to dynamically change the style tag using JavaScript?

Tags:

javascript

css

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

like image 714
Damien Golding Avatar asked Nov 13 '12 08:11

Damien Golding


People also ask

Can JavaScript change the style of an HTML element?

The HTML DOM allows JavaScript to change the style of HTML elements.

Can we change HTML tag dynamically?

Yes!

How do you apply dynamic style?

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.

Can we change CSS dynamically?

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.


2 Answers

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
like image 108
Asad Saeeduddin Avatar answered Oct 05 '22 06:10

Asad Saeeduddin


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!

like image 25
AtheistP3ace Avatar answered Oct 05 '22 08:10

AtheistP3ace