I am using jquery to modify css of a div element on pressing a button. I noticed the css getting inline to the HTML. How can I prevent the style from getting inline ?
Link your stylesheet
in head
<head>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
I am using jquery to modify css of a div element on pressing a button.
The most obvious would of course be to add/remove/toggle a class with a predefined rule, like this,
CSS
.wider {
width: 500px;
}
Script
$( "element" ).toggleClass( "wider" );
but if that is not what you look for, you can add a style element dynamically, to override an existing rule
JS
function loadStyle(css) {
var style = document.querySelector('style[id="lastinbody"]') || document.createElement('style');
style.id = 'lastinbody';
style.type = 'text/css';
if (style.styleSheet){
style.styleSheet.cssText = css;
} else {
style.appendChild(document.createTextNode(css));
}
document.querySelector('body').appendChild(style);
}
Usage
loadStyle('.item { color: red; }');
I noticed the css getting inline to the HTML.
If you want the style being added to the head
, do like this
JS
function loadStyle(css) {
var style = document.querySelector('head style[id="addedinhead"]') || document.createElement('style');
style.id = 'addedinhead';
style.type = 'text/css';
if (style.styleSheet){
style.styleSheet.cssText = css;
} else {
style.appendChild(document.createTextNode(css));
}
document.querySelector('head').appendChild(style);
}
And here is how to push a CSS file
var style = document.createElement('link');
style.rel = 'stylesheet';
style.type = 'text/css';
style.media = 'screen';
style.href = 'css-file-path';
document.querySelector('head').appendChild(style);
And this one shows how to add to an existing linked stylesheet
HTML
<head>
<link title="customCSS" rel="stylesheet" type="text/css" href="style.css">
</head>
JS
function setStyleSheetRule(title, rule) {
for(var i=0; i<document.styleSheets.length; i++) {
var sheet = document.styleSheets[i];
if(sheet.title == title) {
sheet.insertRule(rule, sheet.cssRules.length);
}
}
}
setStyleSheetRule('customCSS', '.have-border { border: 1px solid black;}')
Read more: https://developer.mozilla.org/en-US/docs/Web/API/CSSStyleSheet/insertRule