Change css of static class with javascript [duplicate] - javascript

It's easy to set inline CSS values with javascript. If I want to change the width and I have html like this:
<div style="width: 10px"></div>
All I need to do is:
document.getElementById('id').style.width = value;
It will change the inline stylesheet values. Normally this isn't a problem, because the inline style overrides the stylesheet. Example:
<style>
#tId {
width: 50%;
}
</style>
<div id="tId"></div>
Using this Javascript:
document.getElementById('tId').style.width = "30%";
I get the following:
<style>
#tId {
width: 50%;
}
</style>
<div id="tId" style="width: 30%";></div>
This is a problem, because not only do I not want to change inline values, If I look for the width before I set it, when I have:
<div id="tId"></div>
The value returned is Null, so if I have Javascript that needs to know the width of something to do some logic (I increase the width by 1%, not to a specific value), getting back Null when I expect the string "50%" doesn't really work.
So my question: I have values in a CSS style that are not located inline, how can I get these values? How can I modify the style instead of the inline values, given an id?

Ok, it sounds like you want to change the global CSS so which will effictively change all elements of a peticular style at once. I've recently learned how to do this myself from a Shawn Olson tutorial. You can directly reference his code here.
Here is the summary:
You can retrieve the stylesheets via document.styleSheets. This will actually return an array of all the stylesheets in your page, but you can tell which one you are on via the document.styleSheets[styleIndex].href property. Once you have found the stylesheet you want to edit, you need to get the array of rules. This is called "rules" in IE and "cssRules" in most other browsers. The way to tell what CSSRule you are on is by the selectorText property. The working code looks something like this:
var cssRuleCode = document.all ? 'rules' : 'cssRules'; //account for IE and FF
var rule = document.styleSheets[styleIndex][cssRuleCode][ruleIndex];
var selector = rule.selectorText; //maybe '#tId'
var value = rule.value; //both selectorText and value are settable.
Let me know how this works for ya, and please comment if you see any errors.

Please! Just ask w3 (http://www.quirksmode.org/dom/w3c_css.html)!
Or actually, it took me five hours... but here it is!
function css(selector, property, value) {
for (var i=0; i<document.styleSheets.length;i++) {//Loop through all styles
//Try add rule
try { document.styleSheets[i].insertRule(selector+ ' {'+property+':'+value+'}', document.styleSheets[i].cssRules.length);
} catch(err) {try { document.styleSheets[i].addRule(selector, property+':'+value);} catch(err) {}}//IE
}
}
The function is really easy to use.. example:
<div id="box" class="boxes" onclick="css('#box', 'color', 'red')">Click Me!</div>
Or:
<div class="boxes" onmouseover="css('.boxes', 'color', 'green')">Mouseover Me!</div>
Or:
<div class="boxes" onclick="css('body', 'border', '1px solid #3cc')">Click Me!</div>
Oh..
EDIT: as #user21820 described in its answer, it might be a bit unnecessary to change all stylesheets on the page. The following script works with IE5.5 as well as latest Google Chrome, and adds only the above described css() function.
(function (scope) {
// Create a new stylesheet in the bottom
// of <head>, where the css rules will go
var style = document.createElement('style');
document.head.appendChild(style);
var stylesheet = style.sheet;
scope.css = function (selector, property, value) {
// Append the rule (Major browsers)
try { stylesheet.insertRule(selector+' {'+property+':'+value+'}', stylesheet.cssRules.length);
} catch(err) {try { stylesheet.addRule(selector, property+':'+value); // (pre IE9)
} catch(err) {console.log("Couldn't add style");}} // (alien browsers)
}
})(window);

Gathering the code in the answers, I wrote this function that seems running well on my FF 25.
function CCSStylesheetRuleStyle(stylesheet, selectorText, style, value){
/* returns the value of the element style of the rule in the stylesheet
* If no value is given, reads the value
* If value is given, the value is changed and returned
* If '' (empty string) is given, erases the value.
* The browser will apply the default one
*
* string stylesheet: part of the .css name to be recognized, e.g. 'default'
* string selectorText: css selector, e.g. '#myId', '.myClass', 'thead td'
* string style: camelCase element style, e.g. 'fontSize'
* string value optionnal : the new value
*/
var CCSstyle = undefined, rules;
for(var m in document.styleSheets){
if(document.styleSheets[m].href.indexOf(stylesheet) != -1){
rules = document.styleSheets[m][document.all ? 'rules' : 'cssRules'];
for(var n in rules){
if(rules[n].selectorText == selectorText){
CCSstyle = rules[n].style;
break;
}
}
break;
}
}
if(value == undefined)
return CCSstyle[style]
else
return CCSstyle[style] = value
}
This is a way to put values in the css that will be used in JS even if not understood by the browser. e.g. maxHeight for a tbody in a scrolled table.
Call :
CCSStylesheetRuleStyle('default', "#mydiv", "height");
CCSStylesheetRuleStyle('default', "#mydiv", "color", "#EEE");

I don't know why the other solutions go through the whole list of stylesheets for the document. Doing so creates a new entry in each stylesheet, which is inefficient. Instead, we can simply append a new stylesheet and simply add our desired CSS rules there.
style=document.createElement('style');
document.head.appendChild(style);
stylesheet=style.sheet;
function css(selector,property,value)
{
try{ stylesheet.insertRule(selector+' {'+property+':'+value+'}',stylesheet.cssRules.length); }
catch(err){}
}
Note that we can override even inline styles set directly on elements by adding " !important" to the value of the property, unless there already exist more specific "!important" style declarations for that property.

I don't have rep enough to comment so I'll format an answer, yet it is only a demonstration of the issue in question.
It seems, when element styles are defined in stylesheets they are not visible to getElementById("someElement").style
This code illustrates the issue... Code from below on jsFiddle.
In Test 2, on the first call, the items left value is undefined, and so, what should be a simple toggle gets messed up. For my use I will define my important style values inline, but it does seem to partially defeat the purpose of the stylesheet.
Here's the page code...
<html>
<head>
<style type="text/css">
#test2a{
position: absolute;
left: 0px;
width: 50px;
height: 50px;
background-color: green;
border: 4px solid black;
}
#test2b{
position: absolute;
left: 55px;
width: 50px;
height: 50px;
background-color: yellow;
margin: 4px;
}
</style>
</head>
<body>
<!-- test1 -->
Swap left positions function with styles defined inline.
Test 1<br>
<div class="container">
<div id="test1a" style="position: absolute;left: 0px;width: 50px; height: 50px;background-color: green;border: 4px solid black;"></div>
<div id="test1b" style="position: absolute;left: 55px;width: 50px; height: 50px;background-color: yellow;margin: 4px;"></div>
</div>
<script type="text/javascript">
function test1(){
var a = document.getElementById("test1a");
var b = document.getElementById("test1b");
alert(a.style.left + " - " + b.style.left);
a.style.left = (a.style.left == "0px")? "55px" : "0px";
b.style.left = (b.style.left == "0px")? "55px" : "0px";
}
</script>
<!-- end test 1 -->
<!-- test2 -->
<div id="moveDownThePage" style="position: relative;top: 70px;">
Identical function with styles defined in stylesheet.
Test 2<br>
<div class="container">
<div id="test2a"></div>
<div id="test2b"></div>
</div>
</div>
<script type="text/javascript">
function test2(){
var a = document.getElementById("test2a");
var b = document.getElementById("test2b");
alert(a.style.left + " - " + b.style.left);
a.style.left = (a.style.left == "0px")? "55px" : "0px";
b.style.left = (b.style.left == "0px")? "55px" : "0px";
}
</script>
<!-- end test 2 -->
</body>
</html>
I hope this helps to illuminate the issue.
Skip

You can get the "computed" styles of any element.
IE uses something called "currentStyle", Firefox (and I assume other "standard compliant" browsers) uses "defaultView.getComputedStyle".
You'll need to write a cross browser function to do this, or use a good Javascript framework like prototype or jQuery (search for "getStyle" in the prototype javascript file, and "curCss" in the jquery javascript file).
That said if you need the height or width you should probably use element.offsetHeight and element.offsetWidth.
The value returned is Null, so if I have Javascript that needs to know the width of something to do some logic (I increase the width by 1%, not to a specific value)
Mind, if you add an inline style to the element in question, it can act as the "default" value and will be readable by Javascript on page load, since it is the element's inline style property:
<div style="width:50%">....</div>

This simple 32 lines gist lets you identify a given stylesheet and change its styles very easily:
var styleSheet = StyleChanger("my_custom_identifier");
styleSheet.change("darkolivegreen", "blue");

I've never seen any practical use of this, but you should probably consider DOM stylesheets. However, I honestly think that's overkill.
If you simply want to get the width and height of an element, irrespective of where the dimensions are being applied from, just use element.offsetWidth and element.offsetHeight.

Perhaps try this:
function CCSStylesheetRuleStyle(stylesheet, selectorText, style, value){
var CCSstyle = undefined, rules;
for(var m in document.styleSheets){
if(document.styleSheets[m].href.indexOf(stylesheet) != -1){
rules = document.styleSheets[m][document.all ? 'rules' : 'cssRules'];
for(var n in rules){
if(rules[n].selectorText == selectorText){
CCSstyle = rules[n].style;
break;
}
}
break;
}
}
if(value == undefined)
return CCSstyle[style]
else
return CCSstyle[style] = value
}

Related

How to apply font-size property based on the value of variable passed to css [duplicate]

I have these CSS variables to control the colors of my project so I can do theming.
html {
--main-background-image: url(../images/starsBackground.jpg);
--main-text-color: #4CAF50;
--main-background-color: rgba(0,0,0,.25);
--beta-background-color: rgba(0,0,0,.85);
}
However no matter how I try to change the attribute(the two commented lines tried separately), the closest I get is returning not a valid attribute.
function loadTheme() {
var htmlTag = document.getElementsByTagName("html");
var yourSelect = document.getElementById( "themeSelect" );
var selectedTheme = ( yourSelect.options[ yourSelect.selectedIndex ].value );
// htmlTag[0].setAttribute('--main-text-color', '#FFCF40');
// $("html").css("--main-text-color","#FFCF40");
}
Turns out changing CSS variables is possible using the el.style.cssText property, or el.style.setProperty or el.setAttribute methods. In your code snippets el.setAttribute is incorrectly used, which is causing the error you encountered. Here's the correct way:
document.documentElement.style.cssText = "--main-background-color: red";
or
document.documentElement.style.setProperty("--main-background-color", "green");
or
document.documentElement.setAttribute("style", "--main-background-color: green");
Demo
The following demo defines a background color using a CSS variable, then changes it using the JS snippet 2 seconds after loading.
window.onload = function() {
setTimeout(function() {
document.documentElement.style.cssText = "--main-background-color: red";
}, 2000);
};
html {
--main-background-image: url(../images/starsBackground.jpg);
--main-text-color: #4CAF50;
--main-background-color: rgba(0,0,0,.25);
--beta-background-color: rgba(0,0,0,.85);
}
body {
background-color: var(--main-background-color);
}
This will only work in browsers supporting CSS variables obviously.
If you are using :root:
:root {
--somevar: black;
}
It will be documentElement.
document.documentElement.style.setProperty('--somevar', 'green');
The native solution
The standard methods to get/set CSS3 variables are .setProperty() and .getPropertyValue().
If your Variables are Globals (declared in :root), you can use the following, for getting and setting their values.
// setter
document.documentElement.style.setProperty('--myVariable', 'blue');
// getter
document.documentElement.style.getPropertyValue('--myVariable');
However the getter will only return the value of a var, if has been set, using .setProperty().
If has been set through CSS declaration, will return undefined. Check it in this example:
let c = document.documentElement.style.getPropertyValue('--myVariable');
alert('The value of --myVariable is : ' + (c?c:'undefined'));
:root{ --myVariable : red; }
div{ background-color: var(--myVariable); }
<div>Red background set by --myVariable</div>
To avoid that unexpected behavior you have to make use of the getComputedStyle()method , before calling .getPropertyValue().
The getter will then , look lik this :
getComputedStyle(document.documentElement,null).getPropertyValue('--myVariable');
In my opinion, accessing CSS variables should be more simple, fast, intuitive and natural...
My personal approach
I've implemented CSSGlobalVariables a tiny (<3kb) javascript module wich automatically detects and packs into an Object, all the active CSS global variables in a document, for easier acces & manipulation.
import {CSSGlobalVariables} from './css-global-variables.js';
let cssVar = new CSSGlobalVariables();
// set the CSS global --myColor value to "green"
cssVar.myColor = "green";
Any change applied to the Object properties, is translated automatically to the CSS variables, and viceversa.
Available in : https://github.com/colxi/css-global-variables
You can simply use the standard way of setting arbitrary CSS properties: setProperty
document.body.style.setProperty('--background-color', 'blue');
body {
--background-color: red;
background-color: var(--background-color);
}
For anyone who is struggling with it, if your CSS variable is a sentence you need to wrap it in qoutes.
:root {
--my-css-var: 'Hello Person!';
}
.selector:after {
content: var(--my-css-var);
}
This does not work:
let myVar = 'Hi Person! (doesnt work)';
document.getElementsByTagName('html')[0].style.setProperty('--my-css-var', myVar);
But this does:
let myVar = 'Hi Person! (works)';
document.getElementsByTagName('html')[0].style.setProperty('--my-css-var', '"' + myVar + '"');
You could add something like below (without using class variables)
function loadTheme() {
var htmlTag = document.getElementById("myDiv");
var yourSelect = document.getElementById("themeSelect");
var selectedTheme = (yourSelect.options[yourSelect.selectedIndex].value);
console.log("selected theme: " + selectedTheme);
// reset class names
htmlTag.className = '';
// add selected theme
htmlTag.className = 'theme' + selectedTheme;
}
.theme1 {
color: blue;
}
.theme2 {
color: red;
}
<div id="myDiv">
test
</div>
<select id="themeSelect" onChange="loadTheme()">
<option value="1">Theme 1</option>
<option value="2">Theme 2</option>
</select>
It would probably be easier to define classes in your CSS that contain the various theme styles (.theme1 {...}, .theme2 {...}, etc) and then change the class with JS based on the selected value.

Is there a way to point to document.styleSheets[].cssRules[] using a rule name?

I want to change a specific class-property-value using Javascript, but by the class-name itself and not with any integer as a pointer (cssRules[i]) or looping all classes to find the matching "selectorText" value.
This is for changing the readable on-screen language within the page.
<style id="languages" class="languages" title="languages">
<!--
/* ... more styles ... */
.lang-ita { display : none; }
.lang-eng { display : none; }
/* ... more styles ... */
-->
</style>
<script language="javascript">
<!--
function fxSwitchLanguage(i)
{
/* ... more code ... */
document.getElementById('languages').sheet.cssRules[i].style.setProperty('display','block');
/* ... more code ... */
}
-->
</script>
<button onClick="fxSwitchLanguage(0);">ITA</button>
<button onClick="fxSwitchLanguage(1);">ENG</button>
<br>
<div class="lang-ita">CIAO!</div>
<div class="lang-eng">HELLO!</div>
Of course I set the previous language "display" to "none" before showing only the new selected one.
I would like to have ".cssRules['.lang-eng']" instead of ".cssRules[i]".
Since this document is shared and may be changed by someone else, I really DO prefer to point the class using its name and not any hard-coded integer for obvious stability reasons, moreover I do not want to use a "for" cycle to test the "selectorText" property of each written class (can be easily thousands).
I don't mind any Browsers differences (.cssRules or .rules).
I just want to know if it is possible to have it in the way I'd prefer to.
No, there is no CSSOM API to get a rule (or list of rules) by its selector string. Iterating them to find one is the only way. Of course you wouldn't do this in the fxSwitchLanguage function, everytime it is called, but outside of it, only once when the script is loaded. Then just store references to the relevant rules in a few constants, or a data structure.
But since your goal is to manipulate the rules by JavaScript, I'd go even further and also create them using javascript. That way, you can easily store a reference to them without iteration.
const {sheet} = document.getElementById('languages');
const rules = new Map(['eng', 'ita', 'esp'].map(lang => {
const rule = sheet.cssRules[sheet.insertRule(`.lang-${lang} {
display: none;
}`)]; // yes, it's weird, `insertRule` returns an index
return [lang, rule];
}));
let active = null;
function fxSwitchLanguage(l) {
if (active) rules.get(active).style.display = 'none';
rules.get(l).style.display = 'block';
active = l;
} // or build a toggle or whatever
<style id="languages">
</style>
<button onClick="fxSwitchLanguage('ita');">ITA</button>
<button onClick="fxSwitchLanguage('eng');">ENG</button>
<button onClick="fxSwitchLanguage('esp');">ESP</button>
<br>
<div class="lang-ita">CIAO!</div>
<div class="lang-eng">HELLO!</div>
<div class="lang-esp">HOLA!</div>
from comment here is the idea :
function fxSwitchLanguage(varlang) {
//* test if already created and remove it before update*/
if (document.contains(document.getElementById("langSetting"))) {
document.getElementById("langSetting").remove();
}
//* update language chosen*/
var newStyle = document.createElement("style");
newStyle.setAttribute("id", "langSetting"); //* put a mark on it */
var addContent = ".lang-" + varlang + "{display:block;}";
newStyle.appendChild(document.createTextNode(addContent));
var head = document.getElementsByTagName("head")[0];
head.appendChild(newStyle);
}
[class^='lang'] {display:none;}
<button onClick="fxSwitchLanguage('ita');">ITA</button>
<button onClick="fxSwitchLanguage('eng');">ENG</button>
<hr>
<p class="lang-ita">CIAO!</p>
<div class="lang-eng">HELLO!</div>

How do I edit a CSS variable using JS?

I have these CSS variables to control the colors of my project so I can do theming.
html {
--main-background-image: url(../images/starsBackground.jpg);
--main-text-color: #4CAF50;
--main-background-color: rgba(0,0,0,.25);
--beta-background-color: rgba(0,0,0,.85);
}
However no matter how I try to change the attribute(the two commented lines tried separately), the closest I get is returning not a valid attribute.
function loadTheme() {
var htmlTag = document.getElementsByTagName("html");
var yourSelect = document.getElementById( "themeSelect" );
var selectedTheme = ( yourSelect.options[ yourSelect.selectedIndex ].value );
// htmlTag[0].setAttribute('--main-text-color', '#FFCF40');
// $("html").css("--main-text-color","#FFCF40");
}
Turns out changing CSS variables is possible using the el.style.cssText property, or el.style.setProperty or el.setAttribute methods. In your code snippets el.setAttribute is incorrectly used, which is causing the error you encountered. Here's the correct way:
document.documentElement.style.cssText = "--main-background-color: red";
or
document.documentElement.style.setProperty("--main-background-color", "green");
or
document.documentElement.setAttribute("style", "--main-background-color: green");
Demo
The following demo defines a background color using a CSS variable, then changes it using the JS snippet 2 seconds after loading.
window.onload = function() {
setTimeout(function() {
document.documentElement.style.cssText = "--main-background-color: red";
}, 2000);
};
html {
--main-background-image: url(../images/starsBackground.jpg);
--main-text-color: #4CAF50;
--main-background-color: rgba(0,0,0,.25);
--beta-background-color: rgba(0,0,0,.85);
}
body {
background-color: var(--main-background-color);
}
This will only work in browsers supporting CSS variables obviously.
If you are using :root:
:root {
--somevar: black;
}
It will be documentElement.
document.documentElement.style.setProperty('--somevar', 'green');
The native solution
The standard methods to get/set CSS3 variables are .setProperty() and .getPropertyValue().
If your Variables are Globals (declared in :root), you can use the following, for getting and setting their values.
// setter
document.documentElement.style.setProperty('--myVariable', 'blue');
// getter
document.documentElement.style.getPropertyValue('--myVariable');
However the getter will only return the value of a var, if has been set, using .setProperty().
If has been set through CSS declaration, will return undefined. Check it in this example:
let c = document.documentElement.style.getPropertyValue('--myVariable');
alert('The value of --myVariable is : ' + (c?c:'undefined'));
:root{ --myVariable : red; }
div{ background-color: var(--myVariable); }
<div>Red background set by --myVariable</div>
To avoid that unexpected behavior you have to make use of the getComputedStyle()method , before calling .getPropertyValue().
The getter will then , look lik this :
getComputedStyle(document.documentElement,null).getPropertyValue('--myVariable');
In my opinion, accessing CSS variables should be more simple, fast, intuitive and natural...
My personal approach
I've implemented CSSGlobalVariables a tiny (<3kb) javascript module wich automatically detects and packs into an Object, all the active CSS global variables in a document, for easier acces & manipulation.
import {CSSGlobalVariables} from './css-global-variables.js';
let cssVar = new CSSGlobalVariables();
// set the CSS global --myColor value to "green"
cssVar.myColor = "green";
Any change applied to the Object properties, is translated automatically to the CSS variables, and viceversa.
Available in : https://github.com/colxi/css-global-variables
You can simply use the standard way of setting arbitrary CSS properties: setProperty
document.body.style.setProperty('--background-color', 'blue');
body {
--background-color: red;
background-color: var(--background-color);
}
For anyone who is struggling with it, if your CSS variable is a sentence you need to wrap it in qoutes.
:root {
--my-css-var: 'Hello Person!';
}
.selector:after {
content: var(--my-css-var);
}
This does not work:
let myVar = 'Hi Person! (doesnt work)';
document.getElementsByTagName('html')[0].style.setProperty('--my-css-var', myVar);
But this does:
let myVar = 'Hi Person! (works)';
document.getElementsByTagName('html')[0].style.setProperty('--my-css-var', '"' + myVar + '"');
You could add something like below (without using class variables)
function loadTheme() {
var htmlTag = document.getElementById("myDiv");
var yourSelect = document.getElementById("themeSelect");
var selectedTheme = (yourSelect.options[yourSelect.selectedIndex].value);
console.log("selected theme: " + selectedTheme);
// reset class names
htmlTag.className = '';
// add selected theme
htmlTag.className = 'theme' + selectedTheme;
}
.theme1 {
color: blue;
}
.theme2 {
color: red;
}
<div id="myDiv">
test
</div>
<select id="themeSelect" onChange="loadTheme()">
<option value="1">Theme 1</option>
<option value="2">Theme 2</option>
</select>
It would probably be easier to define classes in your CSS that contain the various theme styles (.theme1 {...}, .theme2 {...}, etc) and then change the class with JS based on the selected value.

Is it possible to change css class properities through javascript? [duplicate]

It's easy to set inline CSS values with javascript. If I want to change the width and I have html like this:
<div style="width: 10px"></div>
All I need to do is:
document.getElementById('id').style.width = value;
It will change the inline stylesheet values. Normally this isn't a problem, because the inline style overrides the stylesheet. Example:
<style>
#tId {
width: 50%;
}
</style>
<div id="tId"></div>
Using this Javascript:
document.getElementById('tId').style.width = "30%";
I get the following:
<style>
#tId {
width: 50%;
}
</style>
<div id="tId" style="width: 30%";></div>
This is a problem, because not only do I not want to change inline values, If I look for the width before I set it, when I have:
<div id="tId"></div>
The value returned is Null, so if I have Javascript that needs to know the width of something to do some logic (I increase the width by 1%, not to a specific value), getting back Null when I expect the string "50%" doesn't really work.
So my question: I have values in a CSS style that are not located inline, how can I get these values? How can I modify the style instead of the inline values, given an id?
Ok, it sounds like you want to change the global CSS so which will effictively change all elements of a peticular style at once. I've recently learned how to do this myself from a Shawn Olson tutorial. You can directly reference his code here.
Here is the summary:
You can retrieve the stylesheets via document.styleSheets. This will actually return an array of all the stylesheets in your page, but you can tell which one you are on via the document.styleSheets[styleIndex].href property. Once you have found the stylesheet you want to edit, you need to get the array of rules. This is called "rules" in IE and "cssRules" in most other browsers. The way to tell what CSSRule you are on is by the selectorText property. The working code looks something like this:
var cssRuleCode = document.all ? 'rules' : 'cssRules'; //account for IE and FF
var rule = document.styleSheets[styleIndex][cssRuleCode][ruleIndex];
var selector = rule.selectorText; //maybe '#tId'
var value = rule.value; //both selectorText and value are settable.
Let me know how this works for ya, and please comment if you see any errors.
Please! Just ask w3 (http://www.quirksmode.org/dom/w3c_css.html)!
Or actually, it took me five hours... but here it is!
function css(selector, property, value) {
for (var i=0; i<document.styleSheets.length;i++) {//Loop through all styles
//Try add rule
try { document.styleSheets[i].insertRule(selector+ ' {'+property+':'+value+'}', document.styleSheets[i].cssRules.length);
} catch(err) {try { document.styleSheets[i].addRule(selector, property+':'+value);} catch(err) {}}//IE
}
}
The function is really easy to use.. example:
<div id="box" class="boxes" onclick="css('#box', 'color', 'red')">Click Me!</div>
Or:
<div class="boxes" onmouseover="css('.boxes', 'color', 'green')">Mouseover Me!</div>
Or:
<div class="boxes" onclick="css('body', 'border', '1px solid #3cc')">Click Me!</div>
Oh..
EDIT: as #user21820 described in its answer, it might be a bit unnecessary to change all stylesheets on the page. The following script works with IE5.5 as well as latest Google Chrome, and adds only the above described css() function.
(function (scope) {
// Create a new stylesheet in the bottom
// of <head>, where the css rules will go
var style = document.createElement('style');
document.head.appendChild(style);
var stylesheet = style.sheet;
scope.css = function (selector, property, value) {
// Append the rule (Major browsers)
try { stylesheet.insertRule(selector+' {'+property+':'+value+'}', stylesheet.cssRules.length);
} catch(err) {try { stylesheet.addRule(selector, property+':'+value); // (pre IE9)
} catch(err) {console.log("Couldn't add style");}} // (alien browsers)
}
})(window);
Gathering the code in the answers, I wrote this function that seems running well on my FF 25.
function CCSStylesheetRuleStyle(stylesheet, selectorText, style, value){
/* returns the value of the element style of the rule in the stylesheet
* If no value is given, reads the value
* If value is given, the value is changed and returned
* If '' (empty string) is given, erases the value.
* The browser will apply the default one
*
* string stylesheet: part of the .css name to be recognized, e.g. 'default'
* string selectorText: css selector, e.g. '#myId', '.myClass', 'thead td'
* string style: camelCase element style, e.g. 'fontSize'
* string value optionnal : the new value
*/
var CCSstyle = undefined, rules;
for(var m in document.styleSheets){
if(document.styleSheets[m].href.indexOf(stylesheet) != -1){
rules = document.styleSheets[m][document.all ? 'rules' : 'cssRules'];
for(var n in rules){
if(rules[n].selectorText == selectorText){
CCSstyle = rules[n].style;
break;
}
}
break;
}
}
if(value == undefined)
return CCSstyle[style]
else
return CCSstyle[style] = value
}
This is a way to put values in the css that will be used in JS even if not understood by the browser. e.g. maxHeight for a tbody in a scrolled table.
Call :
CCSStylesheetRuleStyle('default', "#mydiv", "height");
CCSStylesheetRuleStyle('default', "#mydiv", "color", "#EEE");
I don't know why the other solutions go through the whole list of stylesheets for the document. Doing so creates a new entry in each stylesheet, which is inefficient. Instead, we can simply append a new stylesheet and simply add our desired CSS rules there.
style=document.createElement('style');
document.head.appendChild(style);
stylesheet=style.sheet;
function css(selector,property,value)
{
try{ stylesheet.insertRule(selector+' {'+property+':'+value+'}',stylesheet.cssRules.length); }
catch(err){}
}
Note that we can override even inline styles set directly on elements by adding " !important" to the value of the property, unless there already exist more specific "!important" style declarations for that property.
I don't have rep enough to comment so I'll format an answer, yet it is only a demonstration of the issue in question.
It seems, when element styles are defined in stylesheets they are not visible to getElementById("someElement").style
This code illustrates the issue... Code from below on jsFiddle.
In Test 2, on the first call, the items left value is undefined, and so, what should be a simple toggle gets messed up. For my use I will define my important style values inline, but it does seem to partially defeat the purpose of the stylesheet.
Here's the page code...
<html>
<head>
<style type="text/css">
#test2a{
position: absolute;
left: 0px;
width: 50px;
height: 50px;
background-color: green;
border: 4px solid black;
}
#test2b{
position: absolute;
left: 55px;
width: 50px;
height: 50px;
background-color: yellow;
margin: 4px;
}
</style>
</head>
<body>
<!-- test1 -->
Swap left positions function with styles defined inline.
Test 1<br>
<div class="container">
<div id="test1a" style="position: absolute;left: 0px;width: 50px; height: 50px;background-color: green;border: 4px solid black;"></div>
<div id="test1b" style="position: absolute;left: 55px;width: 50px; height: 50px;background-color: yellow;margin: 4px;"></div>
</div>
<script type="text/javascript">
function test1(){
var a = document.getElementById("test1a");
var b = document.getElementById("test1b");
alert(a.style.left + " - " + b.style.left);
a.style.left = (a.style.left == "0px")? "55px" : "0px";
b.style.left = (b.style.left == "0px")? "55px" : "0px";
}
</script>
<!-- end test 1 -->
<!-- test2 -->
<div id="moveDownThePage" style="position: relative;top: 70px;">
Identical function with styles defined in stylesheet.
Test 2<br>
<div class="container">
<div id="test2a"></div>
<div id="test2b"></div>
</div>
</div>
<script type="text/javascript">
function test2(){
var a = document.getElementById("test2a");
var b = document.getElementById("test2b");
alert(a.style.left + " - " + b.style.left);
a.style.left = (a.style.left == "0px")? "55px" : "0px";
b.style.left = (b.style.left == "0px")? "55px" : "0px";
}
</script>
<!-- end test 2 -->
</body>
</html>
I hope this helps to illuminate the issue.
Skip
You can get the "computed" styles of any element.
IE uses something called "currentStyle", Firefox (and I assume other "standard compliant" browsers) uses "defaultView.getComputedStyle".
You'll need to write a cross browser function to do this, or use a good Javascript framework like prototype or jQuery (search for "getStyle" in the prototype javascript file, and "curCss" in the jquery javascript file).
That said if you need the height or width you should probably use element.offsetHeight and element.offsetWidth.
The value returned is Null, so if I have Javascript that needs to know the width of something to do some logic (I increase the width by 1%, not to a specific value)
Mind, if you add an inline style to the element in question, it can act as the "default" value and will be readable by Javascript on page load, since it is the element's inline style property:
<div style="width:50%">....</div>
This simple 32 lines gist lets you identify a given stylesheet and change its styles very easily:
var styleSheet = StyleChanger("my_custom_identifier");
styleSheet.change("darkolivegreen", "blue");
I've never seen any practical use of this, but you should probably consider DOM stylesheets. However, I honestly think that's overkill.
If you simply want to get the width and height of an element, irrespective of where the dimensions are being applied from, just use element.offsetWidth and element.offsetHeight.
Perhaps try this:
function CCSStylesheetRuleStyle(stylesheet, selectorText, style, value){
var CCSstyle = undefined, rules;
for(var m in document.styleSheets){
if(document.styleSheets[m].href.indexOf(stylesheet) != -1){
rules = document.styleSheets[m][document.all ? 'rules' : 'cssRules'];
for(var n in rules){
if(rules[n].selectorText == selectorText){
CCSstyle = rules[n].style;
break;
}
}
break;
}
}
if(value == undefined)
return CCSstyle[style]
else
return CCSstyle[style] = value
}

How to get a css property of an externally styled element with javascript

lets say i have a div style externally like this
.box{
background: red;
}
then maybe in javascript i want to toggle the background color, so i have to check first if it has a partcular background color before applying
var box = document.querySelector('.box');
if(box.style.background=='red'){
box.style.background='pink';
}else{
box.style.background='red';
}
NOTE: i am not using this for development just a js student
To add a tiny question, if i want to apply css transition to the background change how will that be applied.
the below code works though but i feel there is a cleaner way
if(!box.style.background){ //this is because background property is null when reading from external css
box.style.background='pink';
}else{
box.style.background="";
}
but for the transition i tried applying the transition
box.style.WebkitTransition='background 0.5s easeout';
but didnt transits
To get the computed style of an element (e.g., with stylesheets applied), you use getComputedStyle:
var box = /*...get a specific element...*/;
var style = getComputedStyle(box);
// Use the properties on `style`, which are like the ones on `element.style`
On older IE, you use the currentStyle property of the element instead. You can partially polyfill getComputedStyle like this:
if (!window.getComputedStyle) {
window.getComputedStyle = function(element, pseudoElement) {
if (pseudoElement) {
throw "The second argument for getComputedStyle cannot be polyfilled";
}
return element.currentStyle;
};
}
Example:
if (!window.getComputedStyle) {
window.getComputedStyle = function(element, pseudoElement) {
if (pseudoElement) {
throw "The second argument for getComputedStyle cannot be polyfilled";
}
return element.currentStyle;
};
}
var foo = document.getElementById("foo");
var style = getComputedStyle(foo);
if (style) {
snippet.log("Current color of #foo is: " + style.color);
}
.box {
color: green;
}
<div id="foo" class="box">This is a box</div>
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>

Categories

Resources