Add CSS to specific page via JS

Asked

Viewed 1,444 times

3

I’m currently using Blogger, and I want to add css styles to just one specific page. I used a while ago a standard code from the blogger himself that allowed this (), but it doesn’t work anymore. So I wanted to ask you to give me a JS solution that works the same way. Thanks in advance.

  • 1

    What CSS do you want to add?

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 one link and just need to change the reference, can do so in html:

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

And in Javascript catch 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 which 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>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.