My Technical Notes

Wednesday, 18 June 2014

Adding CSS Dynamically to a page via Javascript/JQuery

Adding CSS dynamically onto a page can be useful if you are making a simple GreaseMonkey script which changes the css styles to make the text more readable. First define a simple function addCss:


function addCss(cssStyles) {
    var styleElem = $('<style>').attr('type', 'text/css').text(cssStyles);
    $('head').append(styleElem);
}
If you do not have JQuery on the page, you can always use vanilla js:

function addCss(cssStyles) {
    var styleElem = document.createElement('style');
    styleElem.type = 'text/css';
    var cssTextNode = document.createTextNode(cssStyles);
    styleElem.appendChild(cssTextNode);
    document.getElementsByTagName('head')[0].appendChild(styleElem);
}
Finally we can add any css we want to:

var cssStyles = 
    [
        'p { color: red; }',
        'div#left-panel { width: 200px; }'
    ].join('\n');

addCss(cssStyles);

No comments: