Add CSS to specific page via JS

3

I'm currently using Blogger, and I want to add css styles to just one specific page. I used a few times ago a default code of the blogger himself that allowed this (), but it does not work anymore. So I wanted to ask you guys to give me a JS solution that works the same way. Thank you in advance.

    
asked by anonymous 25.10.2015 / 17:52

1 answer

2
var FILE = '/assets/css/meucss.css';

var css = document.createElement('link');
css.setAttribute('rel','stylesheet');
css.setAttribute('type', 'text/css');
css.setAttribute('href', FILE);

document.getElementsByTagName('head')[0].appendChild(css);

If you already have a link and just need to change the reference, you can do so in html:

<!-- sem 'href' definido -->
<link rel='stylesheet' type='text/css' id='dinamico'/>

And in Javascript get it by the id attribute:

var FILE = 'meucss.css';
document.getElementById('dinamico').setAttribute('href', FILE);

Furthermore, depending on how you are doing, you can use a single css file and use classes in body to define what rules should be applied in that document. For example:

/**
 * O 'body' de todas as páginas que incluirem esse css será preto.
 */

body { background-color: black }


/**
 * O 'body' das páginas que incluirem a classe 'espefico' será azul.
 */
body.especifico { background-color: skyblue }
<body class='especifico'>
  Qual a minha cor?
</body>
    
25.10.2015 / 18:08