简体   繁体   中英

How to dynamically change the style tag using JavaScript?

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

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!

style is a property. After you getElementById() you can change its style .

HTML:

<div id='myDiv'>...</div>

JS:

var div = document.getElementById('myDiv')

div.style.background = 'red';
div.style.margin = "10px";
div.style.fontSize = "12px";

etc.

A style element has no element children, as its content is by definition just text (as far as HTML is concerned). But this means that you can just append to its content using the innerHTML property. If your element has <style id=foo> , then you write:

document.getElementById('foo').innerHTML += styleContents;

I tossed together a quick example at http://jsfiddle.net/fttS5/1/ .

You can attach an id to the style tags just like you would any other element in HTML.

<style id="style"></style>

Now you can take the code you tried with appendChild and add one quick change to it

document.getElementById('style').appendChild(document.createTextNode(styleContents));

This should do the trick. Good Luck.

You can also just use the innerHTML method listed as the answer below mine.

try this

var currentElement = document.getElementById('style');
var currentStyle = currentElement.getAttribute('style');
var stylePieces = [];
if(currentStyle) {
    stylePieces = currentStyle.split(';');
}
stylePieces.push('new-style: true;');
currentElement.setAttribute('style', stylePieces.join(';'));

Why don't you use the jQuery library and append new CSS to the DOM elements directly?

For example:

<script>
$(document).ready(function(){
    $("#an_element").css("border", "1px solid #333");
});
</script>

<div id="an_element">Test</a>

This would add a border around your element with the ID "an_element".

jQuery Selectors

jQuery CSS

If you want to append rules to an existing style sheet, the official way to do is with the insertRule methods. It will probably be alot easier on the browser then just appending text. Also if you do it like below, if there is a particular css rule is not valid syntax, it will skip it, thus protecting the integrity of your document.

Uses jQuery just for string timming, probably not needed anyway.

You have to give it the ID of the style tag.

function AddMoreStyles(code, styleTagId) {

    var sheet = document.getElementById('#' + styleTagId);

    let lines = code.replace(/[\r\n\t]/gm, ' ').split(/}/);
    if (!sheet) {
        return;
    }
    sheet = sheet.styleSheet || sheet.sheet || sheet;
    lines.forEach(function (str) {
        str = $.trim(str) + '}';
        let m = str.match(/(.+?)\{(.*?)}/), m1, m2;
        if (m) {
            m1 = $.trim(m[1]);
            m2 = $.trim(m[2]);
            try {
                if (sheet.insertRule) sheet.insertRule(m1 + '{' + m2 + '}', sheet.cssRules.length);
                else sheet.addRule(m1, m2);
            } catch (e) {
                console.log("!ERROR in css rule: " + e.message);
            }
        }
    });
};

Adding onto @AtheistP3ace 's answer, here is a function that uses pure JavaScript to change the content of a style block:

// Change the CSS in the style section.
// Property is the name of the class or id E.G. ".mdc-card" or "#main".
// Style is the name of the CSS style. E.G. "Background".
// Value is the setting that the style will use, E.G. "Red"
// WARNING: STOPS AND EXECUTES ON THE FIRST MATCH DOES NOT PROCESS MORE AFTER THAT!!!
function changeCSS(property, style, value, cssSectionID) {
    if (cssSectionID === undefined) {
        cssSectionID = "mainCSS";
    }
    // Get the current CSS sheet.
    var mainCSS = document.getElementById("mainCSS");
    var changeStatus = false;
    // Refine the stylesheet into a more easily processed form.
    // It is done here as making it part of the variable definition produces issues where you still need to call the sheet property.
    mainCSS = mainCSS.sheet;

    // Only execute if the user has specified values for each of the required parameters.
    if (property !== undefined && style !== undefined && value !== undefined) {
        // Loop through all of the CSS Properties until the specified property is found.
        for (var index = 0; index < mainCSS.cssRules.length; index++) {

            // Only apply the value of the property matches.
            if (mainCSS.cssRules[index].selectorText === property.toString()) {
                // Apply the specified property value to the.
                mainCSS.cssRules[index].style[style.toString()] = value.toString();

                // Sets the exit status and breaks the loop's execution.
                changeStatus = true;
                break;
            }
        }   
    }
    // Returns the result of the operation. True being successful and false being unsuccessful.
    return changeStatus;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM