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);
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);
Finally we can add any css we want to:

var cssStyles = 
        'p { color: red; }',
        'div#left-panel { width: 200px; }'


No comments: