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.
4 Answers 4
element.style.width = '50px';
Where element is a reference to the element.
1 Comment
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
1 Comment
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';
1 Comment
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);
}