A function for creating style constructed as follows
function createStyle(css) {
var head = document.head || document.getElementsByTagName("head")[0];
var style = document.createElement("style");
style.type = "text/css";
if(style.styleSheet) {
style.styleSheet.cssText = css;
} else {
var textNode = document.createTextNode(css);
style.append(textNode);
}
head.append(style);
}
inspired by Christoph and TomFuertes code. Then it is called to create a style with class name tab
createStyle(`
.tab button {
background: inherit;
float: left;
outline: none;
border: none;
padding: 8px 6px;
width: 60px;
cursor: pointer;
}
`);
and a HTML element using the style
var div = document.createElement("div");
div.className = "tab";
parent.append(div);
is also created. So it all works.
After that I need to modify the style with class name tab, where following code
var style = document.getElementsByTagName("style");
var css = style[0].innerHTML
var className = css.split(" ")[0].split(".")[1];
is used to get the style class name. I have managed to get the style class name tab and also the string containing the object in css.
The question is how I modify the style without I modify the string and recreate the style? Or if I have to do that, how I should delete the previous defined style if there are already some styles which I have not recorded the order for accessing them through array sytle[].
Proposed solution
Using How to change/remove CSS classes definitions at runtime? suggested by Achu I made this function
// Change style attribute with value
function changeStyleAttribute(style, attr, value) {
var N = document.styleSheets.length;
var styles = document.styleSheets;
for(var i = 0; i < N; i++)
{
if(styles[i].rules[0].selectorText == style)
styles[i].rules[0].style[attr] = value;
}
}
which is called
changeStyleAttribute(".tab", "width", "299px");
and works. I hope there is another better and simpler solution.
You'll want to use document.styleSheets[i].cssRules which is an array you need to parse through to find the one you want, and then rule.style.setProperty('font-size','10px',null);
Refer to this link: How to change/remove CSS classes definitions at runtime?.
Hope this helps.
Related
This question already has an answer here:
Query property value of a css class even if not in use
(1 answer)
Closed 7 years ago.
I dispose of the following class :
.specialCell {
padding-left: 10px;
}
I would like to use this value as a property in JS, eg
var specialCellLeftPadding = getCssValue('.specialCell', 'padding-left');
The only way I can think of would be to create an element with the wanted class and get the seeked attribute value :
var tmpElt = document.createElement('div');
tmpElt.className = 'specialCell';
document.body.appendChild(tmpElt);
var specialCellLeftPadding = getComputedProperties(tmpElt).getPropertyValue('padding-left');
document.body.removeChild(tmpElt);
Is it possible to achieve the same purpose without creating and adding an new element to the dom ? (assuming no element with this class exists).
You can query CSS information directly from stylesheets using the CSSOM. E.g.,
var stylesheet = document.styleSheets[0];
document.getElementById('output').innerHTML = stylesheet.cssRules[0].style.paddingLeft;
.test { padding-left: 12px; }
Padding left: <span id="output"></span>
Borrowing from the example of dystroy's answer, you can get a css value using the document.styleSheets property
Using the css
.specialCell {
padding-left: 10px;
}
and
function getCssProperty(cssclass, property) {
for (var i = 0; i < document.styleSheets.length; i++) {
var styleSheet = document.styleSheets[i];
var cssRules = styleSheet.rules || // chrome, IE
styleSheet.cssRules; // firefox
for (var ir = cssRules.length; ir-- > 0;) {
var rule = cssRules[ir];
if (rule.selectorText == "." + cssclass) {
return rule.style.getPropertyValue(property);
}
}
}
}
var prop = getCssProperty('specialCell', 'padding-left');
console.info(prop);
this example will print 10px in the console
Is it somehow possible to get a style property from a css class that is not used anywhere?
I'd like to read for example the color property that I want to apply to an animation with jquery ui but I want to avoid duplicating them again in the js code.
Let's say I have this:
.default-style {
color: red;
}
.disabled-style {
color: gray;
}
.current-style {}
<span class="current-style">Hello world!</span>
Now I would like to set the .default-style color to the .current-style and then animate the color from the .default-style to the .disabled-style and back on click but I don't know how to get them without creating a hidden element.
var currentColor = ""; // I'm stuck here. Get color from css class?
$("span.abc").animate({ color: currentColor });
You can cheat by creating an element, applying the class, adding the element to the document, getting its color, then removing it. If this is all done in one code block, the user will never see the element:
var div = $("<div>").addClass("default-style").appendTo(document.body);
var color = div.css("color");
div.remove();
Alternately, you can loop through document.styleSheets in the document, and loop through the rules of each stylesheet looking for the one that uses that simple class selector, then look at the styles that rule defines.
Gratuitous snippet: ;-)
var div = $("<div>").addClass("default-style").appendTo(document.body);
var color = div.css("color");
div.remove();
$("<p>The color is: " + color + " (the color of this paragraph)</p>").css("color", color).appendTo(document.body);
.default-style {
color: red;
}
.disabled-style {
color: gray;
}
.current-style {}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<span class="current-style">Hello world!</span>
Side note: jQuery's animate function doesn't animate colors natively, you need to add a plugin to do it (jQuery UI bundles one, but if you're not using jQuery UI, you can just use one of the plugins that does this, such as this one, directly).
Correct Way ! Without cheating the document
var currentColor;
var styleSheets = document.styleSheets;
for(var j=0; !currentColor && j<styleSheets.length; j++)
{
var styleSheet = styleSheets[j];
var cssprops = styleSheet.cssRules || styleSheet.rules; // .rules is for older IE
for (var i = 0; i < cssprops.length; i++) {
if(cssprops[i].selectorText == '.default-style');
currentColor = cssprops[i].style.getPropertyCSSValue('color').cssText;
}
}
$("span.abc").animate({ color: currentColor });
Reference From https://developer.mozilla.org/en-US/docs/Web/API/document.styleSheets
In the code below i have illustrated what I am trying to achieve...
Altering an existing CSS class by adding a new rule to it.
<head>
<style>
h4.icontitle
{font-size: 22pt;}
</style>
</head>
<body>
<script type="text/javascript">
textpercent = 84;
document.styleSheets[1].cssRules.['h4.icontitle'].style.setProperty('-webkit-text-size-adjust', textpercent+'%', null);
</script>
<h4> hello </h4>
</body>
This is for a pre-process element of a site running on screens of different sizes.
The result will be...
h4.icontitle
{font-size: 22pt;
-webkit-text-size-adjust:84%;}
Which will be visible when inspecting the DOM.
Any ideas would be most welcome. Javascript only - no JQuery here...
SOLVED.
After a lot of trial and error, here is a working function that allows javascript to insert styles directly into the CSS
function changeCSS(typeAndClass, newRule, newValue)
{
var thisCSS=document.styleSheets[0]
var ruleSearch=thisCSS.cssRules? thisCSS.cssRules: thisCSS.rules
for (i=0; i<ruleSearch.length; i++)
{
if(ruleSearch[i].selectorText==typeAndClass)
{
var target=ruleSearch[i]
break;
}
}
target.style[newRule] = newValue;
}
Called with
changeCSS("h4.icontitle","backgroundColor", "green");
Hopefully others will find this a useful method to use variables within their CSS in pure javascript.
This function works perfectly for my site.
function changeCSS(typeAndClass, newRule, newValue)
{
var thisCSS=document.styleSheets[0]
var ruleSearch=thisCSS.cssRules? thisCSS.cssRules: thisCSS.rules
for (i=0; i<ruleSearch.length; i++)
{
if(ruleSearch[i].selectorText==typeAndClass)
{
var target=ruleSearch[i]
break;
}
}
target.style[newRule] = newValue;
}
Called with
changeCSS("h4.icontitle","backgroundColor", "green");
/**
Use this to update style tag contents
**/
var css = 'h1 { background: grey; }',
head = document.getElementsByTagName('head')[0],
style = document.createElement('style');
style.type = 'text/css';
if (style.styleSheet){
style.styleSheet.cssText = css;
} else {
style.appendChild(document.createTextNode(css));
}
head.appendChild(style);
To work with elements within body use querySelector to target elements upon their CSS identifier. This should help you
https://developer.mozilla.org/en-US/docs/Web/API/document.querySelector
var el = document.querySelector(".icontitle");
el.setAttribute("style","-webkit-text-size-adjust:84%");
Or you can prepare a css snippet and use it conditionally ex: if "new_css" is the new change then
/**css code in style tag**/
.icontitle{
/**style at initial stage**/
}
.icontitle-new-modified{
/**modified css style at later stage**/
}
//after a condition is satisfied
el.setAttribute("class","icontitle-new-modified");
I put an example together that should suit your needs
DEMO jsFiddle
// this gets all h4 tags
var myList = document.getElementsByTagName("h4"); // get all p elements
// this loops through them until it finds one with the class 'icontitle' then it assigns the style to it
var i = 0;
while(i < myList.length) {
if(myList[i].className == "icontitle") {
myList[i].style.color="red";
}
i++;
}
Try this piece of code
$('h4.icontitle').css('-webkit-text-size-adjust','84%');
This question already has answers here:
Setting CSS pseudo-class rules from JavaScript
(12 answers)
Closed 9 years ago.
I would like to change the style of an element's links using JavaScript. The CSS would look like:
#element a:link {
color: #000;
}
I know that you can change the style of the the element itself, as in:
elementObject.style.color = '#000';
Pseudo-code for what I want would be:
|
V
elementObject.[A:LINK].style.color = "#ff0000";
How can I do this?
the :link :visited are not true CSS elements, but part of the CSS rule, this means you need to edit the rule, change the rule or apply another class...
var css='#element a:link { color: #ff0000 }';
style=document.createElement('style');
if (style.styleSheet)
style.styleSheet.cssText=css;
else
style.appendChild(document.createTextNode(css));
document.getElementsByTagName('head')[0].appendChild(style);
You can loop through links and set the one by one.
<script type='text/javascript'>
function new_window()
{
var anchors = document.getElementsByTagName('a');
for(var i = 0; i < anchors.length; i++)
{
anchors[i].style.color = '#000';
}
}
window.onload = new_window;
</script>
The other way to create a wrapper div with the "wrapper" class name. Then replace its class name to "wrapper2" with JavaScript. After then the rules in the CSS like .wrapper a will be activated.
.wrapper a
{
//normal code
}
.wrapper2 a
{
color: #000;
}
select visited links is javascript isnt possible merely by a selector. have a look at Detect Visited Link In Chrome
and this http://archive.plugins.jquery.com/project/Visited
so if you wanna set the style of a visited/unvisited link using javascript loop through all the links in the body. checking wether they are visited and then apply style.
var as = document.getElementsByTagName('a');
for(var i=0;i<as.length;i++){
//check and set the style here
}
function addCss(sel, css){
S= document.styleSheets[document.styleSheets.length-1];
var r= (S.cssRules!= undefined)? S.cssRules: S.rules;
if(S.insertRule) S.insertRule(sel+'{'+css+'}',r.length);
else if(S.addRule)S.addRule(sel,css,r.length);
}
addCss('button:hover','background-color:blue;');
I have below CSS and and has one JavaScript file where I am getting Width property value say 50px.
I want to put that JavaScript Width property Value to below CSS
.carpe_slider_slitss {
BORDER-LEFT: #5256BB 1px solid; WIDTH: 100px; COLOR: #5256BB;
}
so the above CSS should look likes
.carpe_slider_slitss {
BORDER-LEFT: #5256BB 1px solid; WIDTH: 50px; COLOR: #5256BB;
}
So, how can I pass that JavaScript value to Width property value of CSS.
Please help.
element.style.width = '50px';
Where element is a reference to the element.
You can not manipulate external file via javascript. If your class is located in an external css file then you can not change that.
What all developers do is changing classes that located in current html file or changing style attribute
if you want to change the css styleSheet rules for all elements, you can do that with simple javascript:
function findCssRule(cssSelectorName)
{
var stylesheets = document.styleSheets;
for(var i = 0, ii = stylesheets.length;i<ii;i++)
{
for(var j = 0, jj = stylesheets[i].rules.length;j<jj;j++)
{
if(stylesheets[i].rules[j].selectorText == cssSelectorName)
{
return stylesheets[i].rules[j];
}
}
}
return null;
}
//set the width to 80px for '.carpe_slider_slitss' css rule
var cssRule = findCssRule('.carpe_slider_slitss');
if(cssRule!=null)
cssRule.style.width = '80px';
this is a way to do it
//ether create a new style sheet
var style = document.createElement ("style");
document.getElementByTagName('head')[0].appendChild(style);
//or find a document you want to edit
//ether local
var style = document.getElementByTagName('style')[0];
//or imported
var style = document.getElementByTagName('style')[0];
style = style.sheet ? style.sheet : style.styleSheet;
if(style.insertRule){
//insertRule('your css code',new rule index);
style.insertRule('carpe_slider_slitss{ width: 50px; }', style.cssRules.length); //You can use 0 to insert your rule at the start of the style
}else{ //this is the ie < 9 way
style.addRule('carpe_slider_slitss', 'width: 50px', style.cssRules.length);
}